gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:04:13 26 4
gpt4 key购买 nike

我对这个可能复杂和令人困惑的标题感到非常抱歉,但在试图破坏英语之前,我会把我正在看的东西放在 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;
};

关于c++ - 将函数指针作为参数传递,其中函数指针的参数是函数的函数指针参数的子参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23877510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com