[英]How to use typedef of function signature as type parameter to std::function?
当用作模板类型参数时,函数的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示例 。)
有没有办法使用函数的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从函数指针更改为函数类型。
std::function
需要一个函数类型,而FooFn
是一个指针(to function)类型,而不是函数类型。 使用元编程帮助器模板remove_pointer
进行转换:
typedef std::function<std::remove_pointer<FooFn>::type> TF2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.