c++ - 具有不同参数的回调函数

标签 c++ c

我有两个功能略有不同的函数,所以我不能将它们作为模板函数。

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/

相关文章:

c - time(time_t *timer) 在系统中没有时间漂移的情况下给出错误的结果

c++ - 如何使用FAN_DENY? (法诺菲)

c++ - 合并位移

c++ - 什么时候创建全局变量?

c++ - 在 C++ 中从互斥锁定代码中的函数返回的好方法

c++ - union 和类型双关语

c - 双指针指针

c - 在 C 中调试多进程程序

c++ - 样式化 Qml 桌面组件

c - 在c中定义数据类型的两种方法。我应该选择哪一个?