如何传递函数指针作为模板参数

how to pass function pointer as a template parameter

本文关键字:参数 传递函数 指针      更新时间:2023-10-16

第二行编译得很好,但第三行给出了错误

int (* const f)() = ff;
cout << typeid(replace<int (*)(), int, char>::type).name() << endl;
cout << typeid(replace<f, int, char>::type).name() << endl;
test.cpp:3:25: error: the value of ‘f’ is not usable in a constant expression 
test.cpp:1:15: note: ‘f’ was not declared ‘constexpr’
test.cpp:3:37: error: template argument 1 is invalid

只有当形参是非类型形参时,模板实参才能是函数指针。但遗憾的是,c++ 11甚至还不允许使用各种常量表达式来计算模板实参。对于非类型指针或引用,只允许传递另一个模板形参的值或直接获得的函数或对象的地址,而不能首先将其存储在const/constexpr变量中。

这个限制很可能在下一个c++版本中被取消。

可以使用模板化接口代替函数指针:

template<class T>
class IMyInterface{
public:
 virtual void doSomething(const T& arg) =0;
};