dav*_*bak 5 c++ templates signature
当用作模板类型参数时,函数的 typedef 和使用裸函数类型之间必须有区别。
即,考虑
#include <functional>
typedef std::function<void(int)> TF1;
typedef void(*FooFn)(int);
typedef std::function<FooFn> TF2;
int main() {
TF1 tf1;
TF2 tf2;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我可以创建一个TF1但不能创建一个TF2(错误:)aggregate 'TF2 tf2' has incomplete type and cannot be defined。(见ideone示例。)
有没有办法使用函数(签名)的 typedef 作为模板类型参数;具体来说,作为类型参数std::function?
(没有 C++11 标签,因为我boost::function对非现代编译器也很感兴趣。但如果语言以某种方式改变以启用它,C++11 的答案也将不胜感激。)
对象std::function可以存储任何Callable对象,包括函数指针(您可以tf1使用类型的指针进行初始化FooFn)。
但模板参数的类型是R结果类型和Args实参类型。
template< class R, class... Args >
class function<R(Args...)>;
Run Code Online (Sandbox Code Playgroud)
编辑:以下示例将FooFntypedef 从函数指针更改为函数类型。