如何使用函数签名的 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
需要函数类型,而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
相关文章:
- 为什么std::async使用同一个线程运行函数
- C++ std::regex 使用前瞻失败
- 使用大括号初始化 std::vector 使用初始值设定项列表
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- 为什么 std::vector 使用 std::分配器而不是运算符 new 和 delete?
- 对 std::vector 使用嵌套 [ ] 操作
- std::shared_ptr 使用别名构造函数,是否可以检索初始指针值?
- 我可以对 std::array 使用自定义分配器来获取安全加密密钥吗?
- 通过std::shared_ptr使用Rcpp和RcppParallel的线程安全函数指针
- 对 std::regex_match 使用自定义分配器
- std::out_of_range 使用 libserial 库的 C++ 代码中的错误
- std::exception :使用虚函数和继承与变量
- std::optional - 使用 {} 或 std::nullopt 构造空
- std::bad_weak_ptr使用 shared_from_this 时的异常
- 为什么 std::when_any 使用 std::tuple 而不是 std::vector 作为其结果类型?
- 为什么 std::variant 使用开始和结束迭代器进行编译?
- Std::copy 和 std::ostream_iterator 使用重载函数打印值
- STD :: MAP-使用下标操作员与插入方法添加元素
- 如何避免使用std :: modf使用临时变量
- ::在std之前使用的是什么,例如:: std :: mutex