Jump to content

Welcome to eMastercam

Register now to participate in the forums, access the download area, buy Mastercam training materials, post processors and more. This message will be removed once you have signed in.

Use your display name or email address to sign in:

Using Structs with Function Pointers As Parameters : C++


Recommended Posts

Hi,

I am revising the way I organise my c++ programming.

When we are programming Mastercam, the functions we create have the tendencie to become bloated

requiring many parameters and similar functions that share a lot of code.

In an effort to keep the code short and organized, I came up with this concept :  

#pragma once
//NetLibrary.h
//The ChainAll Parameters struct
//
typedef struct ChainAllParams
{
	int a;
	int b;
};
//
//The ChainAll Functions struct
//
typedef struct ChainAllFunctions
{
	int(*ChainAll)(ChainAllParams params);
};

typedef int(*ChainAll)(ChainAllParams params);
//
//The ChainManagerStruct
//
typedef struct _chainmanager
{
	int result;
	ChainAll chainall;
}ChainManager;
//
//The Chain All function we are passing to the The ChainAll Functions struct
//
int NetChainAll(ChainAllParams params);
//
//The implementation function used
//
int ImplementChainAll(ChainAllParams params, ChainAllFunctions functions);

Now observe how we pass any function we choose to the generic definition in the  ChainAllFunctionsStruct :

NetLibrary.cpp
#include "NetLibrary.h"
//
//
//The Chain All function we are passing to the The ChainAll Functions struct
//
int NetChainAll(ChainAllParams params)
{
	return params.a + params.b;
}
//
//The implementation function used to determine which function to call
//
int ImplementChainAll(ChainAllParams params, ChainAllFunctions functions)
{
	ChainManager str_obj;
	str_obj.chainall = functions.ChainAll;
	str_obj.result = str_obj.chainall(params);
	return str_obj.result;
}

void main()
{
	ChainAllParams params;
	ChainAllFunctions functions;
	functions.ChainAll = NetChainAll;
	params.a = 5;
	params.b = 5;
	System::Console::WriteLine(ImplementChainAll(params,functions));

	System::Console::ReadLine();
}

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.

Join us!

eMastercam - your online source for all things Mastercam.

Together, we are the strongest Mastercam community on the web with over 56,000 members, and our online store offers a wide selection of training materials for all applications and skill levels.

Follow us

×
×
  • Create New...