如何使用函数签名的typedef作为std::function的类型参数?
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 example。)
有没有办法使用函数(签名)的typedef作为模板类型参数;具体来说,作为 std::function
?
的类型参数
(没有 C++11 标签,因为我对 boost::function
以及非现代编译器也很感兴趣。但是,如果语言以某种方式发生了变化,那么 C++11 的答案也将不胜感激启用它。)
std::function
对象可以存储任何 Callable 对象,包括函数指针(您可以使用 FooFn
类型的指针初始化 tf1
).
但是模板参数的类型是 R
结果类型和 Args
个参数。
template< class R, class... Args >
class function<R(Args...)>;
编辑:
以下示例将 FooFn
typedef 从函数指针更改为函数类型。
std::function
需要函数类型,而 FooFn
是指针(指向函数)类型,而不是函数类型。使用元编程助手模板remove_pointer
进行转换:
typedef std::function<std::remove_pointer<FooFn>::type> TF2;
函数的 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 对象,包括函数指针(您可以使用 FooFn
类型的指针初始化 tf1
).
但是模板参数的类型是 R
结果类型和 Args
个参数。
template< class R, class... Args >
class function<R(Args...)>;
编辑:
以下示例将 FooFn
typedef 从函数指针更改为函数类型。
std::function
需要函数类型,而 FooFn
是指针(指向函数)类型,而不是函数类型。使用元编程助手模板remove_pointer
进行转换:
typedef std::function<std::remove_pointer<FooFn>::type> TF2;