将函数指针作为参数传递,其中函数指针的参数是函数的函数指针参数的子项

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

本文关键字:函数 指针 参数 参数传递      更新时间:2023-10-16

我对这个可能很复杂和令人困惑的标题感到非常抱歉,但在试图破坏英语之前,我将把我正在看的东西放在c++代码中。

//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);

这让我很困惑,因为我需要传递一个函数指针给一个函数,但是这个函数指针的参数是不同的。我将传递多个不同的函数指针给这个函数,因为它保存了一个函数指针的列表。每个函数指针都有一个唯一的id,用于调用函数,然后参数通过它传递,例如void CallFunction(unsigned int FuncId, Parameters* param)。这不是确切的系统,因为那是专有的,但它利用了相同的概念。对于所有密集的目的,这些函数都是全局的。此外,我想保持我正在努力创建的系统,但如果我有类似的更好的东西,我会很高兴采用它。

您可以将函数更改为接受void *作为参数。

//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
}

当然,将正确的形参传递给函数非常重要,因为编译器不再检查类型安全。

下面的答案:

我刚刚注意到你的注释,为了确保类型安全(假设你真的想保持'函数指针'方法),你可以向基本参数结构添加一个成员,例如int ParameterType,并在调用的函数中检查。

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