C++ std::bind函数

std::bind();就是用来包装函数,并且可以指定传入几个参数。。。

看下面的例子就明白了

  • placeholders: 占位符,代表第几个参数,比如placeholders::_1代表第一个参数。
  • std::bind()返回值是函数指针,并且通过std::bind();传入的参数可以确定有函数指针的形式。这样完成了对一个想要的函数的封装。
#include <iostream>
#include <functional>
using namespace std;


void func1(int n1, int n2, int n3)
{
    cout << n1 << ' ' << n2 << ' ' << n3  << endl;
}

void test1_1()
{
    auto f1 = std::bind(func1, placeholders::_1, 101, placeholders::_2);
    f1(11, 22);   // same as call func1(11, 101, 22)
}

  • std::bind()调用类方法:因为类非static方法的调用必须要传入调用此方法的对象,所以bind的第二个参数为&foo.
#include <functional>
#include <iostream>
using std::cout;

struct Foo {
    void print_sum(int n1, int n2)
    {
        std::cout << n1 << n2 << '\n';  // 95 5
    }
    int data = 10;
};
int main() 
{
    Foo foo;
    auto f = std::bind(&Foo::print_sum, &foo, 95, std::placeholders::_1);
    f(5); // 100
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值