[C/C++11]_[初级]_[std::bind介绍和使用]
来源:互联网 发布:精易论坛淘宝采集 编辑:程序博客网 时间:2024/06/05 00:35
场景
1.C++11 引入了std::function 对象, 这个对象可以通过std::bind封装所有的函数, 并通过代理调用这个std::function的方式调用这个函数. 比如通过统一的方式调用不定参数个数的函数. 这对实现代理模式等设计模式帮助是很大的.
说明
1.cppreference 上的使用例子我就不多说了, 除了可以用在标准库上, 也是可以用在自己设计带代码结构里. 和 boost.bind
,boost.function
基本一样.
2.以下例子说明如何封装线程函数, 可以指定任意个数参数的函数作为线程执行函数, 和std::thread
类似.
// test-bind.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <Windows.h>#include <iostream>#include <functional>#include <memory>void CountLine(const std::wstring& path){ std::cout << (int*)&path << std::endl; std::wcout << path.c_str() << std::endl;}void AddNumber(int a,int b,long* sum){ *sum = a+b;}class MyThread{public: MyThread(std::function<void()> func) { func_ = func; } static DWORD WINAPI ThreadFunc1(LPVOID param) { std::function<void()>& func = *(std::function<void()>*)param; func(); return 0; } void Run() { thread_ = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) ThreadFunc1, (LPVOID)&func_, 0, NULL); WaitForSingleObject(thread_, INFINITE); } HANDLE thread_; std::function<void()> func_;};MyThread* DoTask1(){ std::wstring path(L"C:\\p"); std::cout << (int*)&path << std::endl; CountLine(path); auto thread = new MyThread(std::bind(CountLine,path)); return thread;}MyThread* DoTask2(long* sum){ auto thread = new MyThread(std::bind(AddNumber,1,2,sum)); thread->Run(); return thread;}int _tmain(int argc, _TCHAR* argv[]){ auto thread = DoTask1(); thread->Run(); long sum = 0; thread = DoTask2(&sum); thread->Run(); std::cout << sum << std::endl; return 0;}
输出:
003DFC84003DFC84C:\p005183F8C:\p3
参考
以boost::function和boost:bind取代虚函数
std::bind
std::function
0 0
- [C/C++11]_[初级]_[std::bind介绍和使用]
- [C/C++11]_[初级]_[使用std::tuple元组-固定大小的集合]
- [C/C++11]_[初级]_[使用std::function来封装函数]
- [C++/object c]_[初级]_[std::map容器的使用总结和NSDictionary词典使用总结]
- [C/C++标准库]_[初级]_[std::deque和std::vector比较]
- [C/C++11语法]_[初级]_[lamba 表达式介绍]
- [C/C++标准库]_[初级]_[std::map的使用细节]
- [C/C++标准库]_[初级]_[使用std::sort排序各种类型数据]
- [C/C++]_[初级]_[使用C字符串(或者std::string)处理函数获取文件所在目录
- [C/C++11]_[初级]_[使用enumerations类型]
- [C/C++]_[初级]_[把一个图片的数据存入到std::string里,使用_wfopen生成二进制文件]
- [C/C++]_[初级]_[标准字符串std::string 所有函数的用法总结]
- [C/C++]_[初级]_[关于std::string的compare陷阱]
- [C/C++]_[初级]_[static_cast,reinterpret_cast,dynimic_cast的使用场景和区别]
- [C/C++]_[初级]_[原子操作]
- [C/C++标准库]_[初级]_[使用string stream]
- [C/C++标准库]_[初级]_[自定义std::map的key]
- [C/C++标准库]_[初级]_[std::vector的删除元素]
- php 读取TXT文本生成 想要的数据格式
- 【VS开发】【miscellaneous】 Windows下配置Git
- HandlerThread深入理解
- Android Studio设置注释模板
- xml可以分页案例
- [C/C++11]_[初级]_[std::bind介绍和使用]
- centos命令
- Linux下察看swap分区大小及增加分区大小
- win7下的Django学习
- MySQL 存储引擎
- Codeforces Round #392(Div. 2) B Blown Garland【暴力枚举】
- linux 下查看tomcat版本
- 图像拼接一般流程
- Android 应用开发学习 (1):物理小球 与 粒子特效