[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
原创粉丝点击