Search code examples
c++pointersfunction-pointersfunction-parameter

Pass Function Pointer as Parameter where the function pointer's parameter is a child of the function's function pointer parameter


I am very sorry for the potentially complicated, and confusing, title, but before trying to destroy the English language, I will just put what I am looking at in C++ code.

//The parent struct
struct Parameters
{ 
};
//the derived struct
struct ParametersDerived : public Paramters
{
     //Paramters
     int paramData;

     //return values
     int retData;
};

//the function i am passing the function pointer to
void Function(void(*FunctionPointer)(Parameters*));

//the function pointer i am passing to the function
void FunctionToPass(ParametersDerived* param)
{
//TODO: do stuff here
}

//Call the function with the function pointer
Function(FunctionToPass);

This is seriously confusing me, because I need to pass a function pointer to a function, but the parameters of said function pointer will vary. I will be passing multiple different function pointers to this function, because it keeps a list of the function pointers. Each of the function pointers has a unique id that is used to call the function, then the parameters is passed through that e.g. void CallFunction(unsigned int FuncId, Parameters* param). This is not the exact system, because that is proprietary, but it utilizes the same concept. For all intensive purposes, the functions are ALL global. Also, I would like to keep the system I am trying to create, but If i had something similar that was better, I would be glad to adopt it.


Solution

  • You could change the functions to take a void * as argument.

    //the function i am passing the function pointer to
    void Function(void(*FunctionPointer)(void*));
    
    //the function pointer i am passing to the function
    void FunctionToPass(void* voidparam)
    {
        ParametersDerived* param = (ParametersDerived*)voidparam;
        //TODO: do stuff here
    }
    

    Of course, it is very important that the right parameters are passed to the functions, because the compiler cannot check the type safety anymore.

    ANSWER DOWN HERE:

    I have just noticed your comment, to ensure type safety (assuming you really want to keep the 'function pointer' approach), you could add a member to the base parameter structure, for example int ParameterType, and check that in the called functions.

    //The parent struct
    struct Parameters
    { 
        int ParameterType;
    };