如何使用函数签名的 typedef 作为 std::function 的类型参数

How to use typedef of function signature as type parameter to std::function?

本文关键字:std 何使用 function 类型参数 作为 typedef 函数      更新时间:2023-10-16

用作模板类型参数时,函数的 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需要函数类型,而FooFn是指针(指向函数(类型,而不是函数类型。 使用元编程帮助程序模板remove_pointer进行转换:

typedef std::function<std::remove_pointer<FooFn>::type> TF2;

std::function对象可以存储任何 Callable 对象,包括函数指针(您可以使用 FooFn 类型的指针初始化tf1(。

但模板参数的类型R结果类型和Args参数。

template< class R, class... Args >
class function<R(Args...)>;

编辑:下面的示例将FooFn typedef 从函数指针更改为函数类型。

https://ideone.com/XF9I7N