std::function & Functor(用 Functor 构造std::function时的注意点)
2016-03-03 16:04
453 查看
std::function 可以保存一切可调用的对象( Functor, lamda,bind对象)
std::funciton 可以复制该对象然后绑定复制后的对象的operator()——传值,也可以直接绑定该对象的operator() ——传引用。
std::bind 同样可以复制该对象,然后绑定复制后的对象的某个函数,也可以直接绑定到该对象上。
Functor:
std::function
因此,在将 Functor 保存到 std::function的时候要考虑类成员的可复制性( 和 move),或者使用最后的make_shared+bind的方法,否则会编译不通过问题。
see link:
http://blog.csdn.net/GW569453350game/article/details/46649517
https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.6/a00481.html
http://stackoverflow.com/questions/27953336/constructing-stdfunction-target-in-place
std::funciton 可以复制该对象然后绑定复制后的对象的operator()——传值,也可以直接绑定该对象的operator() ——传引用。
std::bind 同样可以复制该对象,然后绑定复制后的对象的某个函数,也可以直接绑定到该对象上。
std::binduses value semantics by default, but you can use
std::ref
Functor:
class Functor { public: Functor()=default; // 注意, 在 c++11中,如果声明了其中一个特殊函数(如,复制构造),则编译器不会默认生成另外的特殊函数(如这个构造函数),需要显示声明! int operator() (int a, int b) { return a+b; } private: Functor(const Functor&); // 不能复制,for test }
std::function
#include <functional> #include <memory> #include <iostream> int main() { Functor f; // 这里会调用的是 Functor 的复制构造函数,如果不能复制则不能编译通过。 // 调用 a 将调用复制构造后的新对象的 operator() std::function<int(int, int)> a = f; // 如果 Functor不能够被复制,或者Functor中有成员变量不能够被复制(即默认复制构造失败),则不能够直接用Functor对象来构造 std::function 对象 // 不过下面这样是可以的(不会触发Functor任何构造函数), 只不过要确保在b的生存周期内f一直有效。 // 调用 b 将调用原对象 f 的 operator() std::function<int(int, int)> b = std::ref(f); // 另外,如果Functor提供了 move 构造函数,则下面会调用Functor 的 move 构造函数, 如果不能被move则会被copy构造(因此,复制构造函数也必须显示写出,否则编译不通过) std::function<int(int, int)> c = Functor(); // 这样可以,只会调用Functor的构造函数,不会触发复制构造或move构造, good! std::function<int(int, int)> d = std::bind(&Functor::operator(), std::make_shared<Functor>(), std::placeholders::_1, std::placeholders::_2); return 0; }
因此,在将 Functor 保存到 std::function的时候要考虑类成员的可复制性( 和 move),或者使用最后的make_shared+bind的方法,否则会编译不通过问题。
see link:
http://blog.csdn.net/GW569453350game/article/details/46649517
https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.6/a00481.html
http://stackoverflow.com/questions/27953336/constructing-stdfunction-target-in-place
相关文章推荐
- windows下编译Matconvnet的方法(CPU和GPU)
- 求解逆序对数的几种方法
- 标签库描述文件TLD
- 最长公共子序列问题-HD1423
- andrAndroid 权限
- html meta标签
- beta分布 and Dirichlet分布
- 1016 Phone Bills
- flex remoteobject 调用java重载函数
- Selenium获取input输入框中值的三种方法
- 再谈SQL Server中日志的的作用
- 算法导论:第8章 线性时间排序__基数排序
- JQuery html工具函数
- sed行处理详解 :交换行,合并行,删除行
- context-params与init-params
- --with-http_realip_module选项(后台Nginx服务器记录原始客户端的IP地址 )
- JAVA中的MD5加密,常见问题处理
- Dynamics CRM2013 从subgrid中打开快速创建窗体创建数据
- uva 12296 切割凸多边形
- Dynamics CRM2013 从subgrid中打开快速创建窗体创建数据