将函数指针作为参数传递,其中函数指针的参数是函数的函数指针参数的子项
Pass Function Pointer as Parameter where the function pointer's parameter is a child of the function's function pointer parameter
我对这个可能很复杂和令人困惑的标题感到非常抱歉,但在试图破坏英语之前,我将把我正在看的东西放在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;
};
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针