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对象。

转载于:https://www.cnblogs.com/xiaohaige/p/7700579.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值