std::bind()函数的使用

C++11中提供了std::bind。bind()函数的意义就像它的函数名一样,是用来绑定函数调用的某些参数的。

bind的思想实际上是一种延迟计算的思想,将可调用对象保存起来,然后在需要的时候再调用。而且这种绑定是非常灵活的,不论是普通函数、函数对象、还是成员函数都可以绑定,而且其参数可以支持占位符。

bind()函数常用于,绑定回调函数。

1. bind()绑定静态函数

#include <functional>		// std::bind() 函数在头文件<functional>中
#include <iostream>

// 定义一个简单的静态函数
void print_fruit(std::string fruit_1, std::string fruit_2)		
{
    std::cout << "fruit_1: " << fruit_1 <<std::endl;
    std::cout << "fruit_2: " << fruit_2 <<std::endl;
}

int main()
{
    // 将静态函数print_fruit绑定到fo,并传入参数
    // 其中print_fruit是要绑定的静态函数,后面是需要传入得参数
    // std::placeholders::_2为占位符,表示第二个参数的位置  
    auto fo = bind(&print_fruit, std::placeholders::_1 ,"banana");	
    fo("apple");   
}
// 上述程序输出的结果为:
// fruit_1: apple
// fruit_2: banana

注意:

  • bind()函数的第一个参数为需要绑定的函数,后面为该函数需要传入的参数。
  • 参数的传入,可以直接传入值,也可以使用占位符。
  • 占位符必须从std::placeholders::_1开始以此类推,占位符的顺序可以打乱,运行会自动根据占位符的位置,按顺序排序。(详见2中的例子的输出结果)
  • 第一个参数的占位符:std::placeholders::_1
  • 第二个参数的占位符:std::placeholders::_2 以此类推
  • bind的返回值是可调用实体,可以直接赋给std::function对象

2. bind() 函数在非静态函数,成员函数的使用

在类中,使用bind()绑定类的成员函数时,需要引入this作为第一个参数,用来访问当前所在的类。其他参数和绑定静态参数时相同。

#include <functional>
#include <iostream>

// 定义类
class Fruit{
public:
    void print_fruit(std::string fruit_1,std::string fruit_2,std::string fruit_3);
    void bind_test();
};

void Fruit::print_fruit(std::string fruit_1,std::string fruit_2,std::string fruit_3)
{
    std::cout << "fruit_1: " << fruit_1 << std::endl;
    std::cout << "fruit_2: " << fruit_2 << std::endl;
    std::cout << "fruit_3: " << fruit_2 << std::endl;
}

void Fruit::bind_test()
{
    // 绑定类中成员函数,用this作为第一个参数,来访问该类
    // 注意变量中占位符的位置,及引用时变量传入参数的位置
    auto foo = std::bind(&Fruit::print_fruit, this, "apple_0",std::placeholders::_2,std::placeholders::_1);
    foo("apple_2","apple_3");
}
int main()
{
    Fruit test;
    test.bind_test();
}

// 上述程序输出的结果为:
// fruit_1: apple_0
// fruit_2: apple_3
// fruit_3: apple_2

本文参考:

  • https://blog.csdn.net/u013654125/article/details/100140328

  • https://www.cnblogs.com/BluceLee/p/9323945.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值