Sign in to follow this  
content creator

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();
}

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • 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