繁体   English   中英

如何使用函数签名的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示例 。)

有没有办法使用函数的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

std::function需要一个函数类型,而FooFn是一个指针(to function)类型,而不是函数类型。 使用元编程帮助器模板remove_pointer进行转换:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM