您的位置:首页 > 编程语言 > C语言/C++

[C/C++11]_[初级]_[std::bind介绍和使用]

2017-01-20 14:01 246 查看

场景

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;
}


输出:

003DFC84
003DFC84
C:\p
005183F8
C:\p
3


参考

以boost::function和boost:bind取代虚函数

std::bind

std::function
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: