std::function 和 std::bind 的用法

参考博客:【C++】C++11的std::function和std::bind用法详解_c++中的std中的方法-CSDN博客

直接上代码,不多bb:

std::function 

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

typedef std::function<int(int, int)> com;
typedef std::function<int(int, int, int)> comAdd;

int add(int a, int b, int c)
{    
    return a + b + c;
}

int sub(int a, int b)
{
    return a - b;
}

class multiply{
public:
    int operator()(int a, int b) { return a * b; }
}

auto divide = [](int a, int b)
{
    return a / b;
};

int main()
{
    // 测试std::function
    comAdd c1 = add;
    com c2 = sub;
    com c3 = multiply;
    cout << c1(1, 3, 5) << endl;
    cout << c2(1, 3) << endl;
    cout << c3(1, 3) << endl;

    // 测试std::bind
    auto f1 = bind(add, 1, 2, 3);
    cout << f1() << endl;

    auto f2 = bind(sub, std::placeholder::_1, 4);
    cout<< f2(0) << endl;

    auto f3 = bind(std, std::placeholder::_1, std::placeholder::_2);
    cout<< f3(0, 5) << endl;

    // 测试std::function
    std::function<int(int, int, int)> f4 = std::bind(add, std::placeholder::_1, 9, 9);
    cout<< f4(1, 0, 0) <<endl;

    std::function<int(int, int, int)> f5 = std::bind(add, 9, 9, 9);
    cout<< f5(0, 1, 1) <<endl;

    std::functoin<int(int, int)> f6 = std::bind(divide, 6, 3);
    cout<< f6(9, 3) <<endl;

    return 0;
}

输出结果:

9
-2
3
6
-4
-5
19
27
2

简单总结一下就是:

  • std::function把有"函数功能"的东西给统一了一下,全部当成一个对象来用,方便了很多。其中有:
    • 函数
    • 函数对象(重载了operator()的class)
    • lambda表达式
    • 函数指针
  • std::bind可看作一个函数适配器,绑定一个可调用对象,然后生成一个新的可调用对象。并且可以给它指定一个参数列表。
    • 其中的std::placeholder::_1代表传入用户定义的第一个参数
    • 因为bind的结果是一个可调用的新对象,因此可以赋给std::function
  • 若bind的结果赋给function,则在使用时需要严格按照function中定义的参数个数规定
  • 若bind的结果不赋给function,则使用时不需要严格定义,直接按照bind时的参数定义
  • 在这个例子中,function对象传入的参数由bind确定,而不是用户指定的(cout后面的)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值