c++11 std::bind

#include <iostream>
#include <functional>
using namespace std;

int TestFunc(int a, char c, float f)
{
    cout << a << endl;
    cout << c << endl;
    cout << f << endl;

    return a;
}

int main()
{
    auto bindFunc1 = bind(TestFunc, std::placeholders::_1, 'A', 100.1);
    bindFunc1(10);

    cout << "=================================\n";

    auto bindFunc2 = bind(TestFunc, std::placeholders::_2, std::placeholders::_1, 100.1);
    bindFunc2('B', 10);

    cout << "=================================\n";

    auto bindFunc3 = bind(TestFunc, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);
    bindFunc3(100.1, 30, 'C');

    return 0;
}

1、上面这个代码是对std::bind的一个简单的使用,也很好的描述了std::bind的使用。std::bind就是一个对函数和函数参数的绑定,

2、上面这段代码主要说的是bind中std::placeholders的使用。 std::placeholders是一个占位符。

  当使用bind生成一个新的可调用对象(可以说是一个函数了,但是也不一定)时,std::placeholders表示新的可调用对象的第 几个参数和原函数的第几个参数进行匹配

3、std::placeholders::_1中的,_1表示的是该可调用对象的第一个参数,_2就是第二个参数了,以此类推,但这是有限制的20。

4、当然大家也看到了,除了绑定的std::placeholders::_1这些的绑定,还有的就是默认传参的

5、bind的返回值是可调用实体,可以直接赋给std::function对象。

posted @ 2017-10-20 17:26  _xiaohaige  阅读(179)  评论(0编辑  收藏  举报