我有两个功能略有不同的函数,所以我不能将它们作为模板函数。
int func64(__int64 a) {
return (int) a/2;
}
int func32(int a) {
return a--;
}
根据变量 b64,我想调用 func64 或 func32。我不想在我的代码中多次检查 b64 是否为真,所以我使用指向函数的指针。
void do_func(bool b64) {
typedef int (*pfunc32)(int);
typedef int (*pfunc64)(__int64);
pfunc32 call_func;
if (b64)
call_func = func64; //error C2440: '=' : cannot convert from 'int (__cdecl *)(__int64)' to 'pfunc32'
else
call_func = func32;
//...
call_func(6);
}
如何避免此错误并将 call_func 转换为 pfunc32 或 pfunc64?
最佳答案
该语言要求通过同一函数指针调用的所有函数都具有相同的原型(prototype)。
根据您想要实现的目标,您可以使用已经提到的指针/强制转换方法(在失去类型安全性的情况下满足此要求)或改为传递一个 union :
union u32_64
{
__int64 i64;
int i32;
};
int func64(union u32_64 a) {
return (int) a.i64/2;
}
int func32(union u32_64 a) {
return --a.i32;
}
void do_func(bool b64) {
typedef int (*pfunc)(union u32_64);
pfunc call_func;
if (b64)
call_func = func64;
else
call_func = func32;
//...
union u32_64 u = { .i64 = 6 };
call_func(u);
}
关于c++ - 具有不同参数的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22424969/