当用作模板类型参数时,函数的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;
}
我可以创建一个
TF1
,但不能创建TF2
(错误:aggregate 'TF2 tf2' has incomplete type and cannot be defined
)。 (请参阅ideone example。)有没有一种方法可以将函数(签名)的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...)>;
编辑:
以下示例将
FooFn
typedef从函数指针更改为函数类型。https://ideone.com/XF9I7N
关于c++ - 如何使用函数签名的typedef作为std::function的类型参数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48532500/