在 C++ 中使用模板回调函数

Fla*_*ire 5 c++ templates callback c2664

我想要一个基于给定回调函数检查某些条件的函数。

考虑这个代码:

class Foo{
template <class ParamType>
struct IsGood
{
    typedef bool (*Check)(typename const ParamType*, int other);
};
template< typename ParamType >
void DoSmth(IsGood<ParamType>::Check isGood, const ParamType* param){
   //...
   if(isGood(param, some_int_calculated_here)) doSmthElse();
}
Run Code Online (Sandbox Code Playgroud)

我想要的是这样称呼它:

bool checkEqualInt(int* i, int j){return *i==j;}
bool checkEqualFloat(float* i, float j){return *i==j;}

DoSmth(checkEqualInt, &i);
DoSmth(checkEqualFloat, &i_float);
Run Code Online (Sandbox Code Playgroud)

(所有构造的例子来说明问题)

编译器不会得到它,并抛出错误 C2664“不可能在 bool(ParamType,int) 中从 bool(int*,int) 转换参数 1”

我有一个不使用的解决方案

template< typename ParamType, Check >
void DoSmth(Check isGood, const ParamType param)
Run Code Online (Sandbox Code Playgroud)

哪个省略了检查功能的必要声明?

最好的解决方案是在函数本身中获取 IsGood() 标头。

Dav*_*eas 5

问题是模板函数的第一个参数不可推导:

template< typename ParamType >
void DoSmth(typename IsGood<ParamType>::Check isGood, const ParamType param)
//          ^        ^^^^^^^^^^^^^^^^^^^^^^^^
//          missing  nested type! not deducible!
Run Code Online (Sandbox Code Playgroud)

简单的选项是就地扩展签名(C++03、C++11):

template< typename ParamType >
void DoSmth(void (*isGood)(ParamType,int), const ParamType param)
// note: dropped 'const' that will be dropped anyway by the compiler
Run Code Online (Sandbox Code Playgroud)

IsGood<ParamType>::Check或者,如果您有 C++11,您可以用模板别名替换:

template <typename T>
using IsGood = void (*)(T,int);
template< typename ParamType >
void DoSmth(IsGood<ParamType> isGood, const ParamType param)
Run Code Online (Sandbox Code Playgroud)

或者重构您的代码以采用函子,这将使其更加灵活、简单并且可能高效,因为编译器将更容易内联调用:

template <typename P, typename T>
void DoSmth(P predicate, T param) {
   if (predicate(param,somethingelse)) { ...
}
Run Code Online (Sandbox Code Playgroud)


mfo*_*ini 3

使用函子模板将解决您的问题:

template< typename Functor, typename ParamType >
void DoSmth(Functor isGood, const ParamType param){
   //...
   if(isGood(param, some_int_calculated_here)) doSmthElse();
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用具有兼容签名的任何函数或函子对象(不一定是采用 aParamType和 anint作为参数的函数或函子对象)。否则,您将需要使用具有该确切签名的函数。