c++11 bind直接绑定未初始化类的成员函数、函数对象(functionobject)的方法与区别

c++11 bind直接绑定未初始化类的成员函数、函数对象(functionobject)的方法与区别,第1张

针对标题的两种情况,使用起来有一定的特殊性,特此记录下。



至于其他常规的bind使用方法,网上有很多文章有介绍,也可以看这篇文章。


标题的两种情况:
情况一:

情况二(标黄部分,其他的属于常规bind的用法):

看下面的例子直接学习用法即可,用法也很直观简单,不得不说,C++11的bind的真是太牛叉了!

#include 
#include 
#include 

using namespace std;
using namespace placeholders;

class C {
 public:
    C() {

    }
    C(int x) {
        a = x;
    }
    int operator () (int x, int y) const {
        return a + x + y;
    }

    int fun (int x) {
        a = x;
        return a;
    }

    int a = 1;
};

int main () {
    auto f1 = bind(&C::fun, C(), _1);
    cout << f1(2) << endl;
    auto f2 = bind(f1, 3);
    cout << f2() << endl;
    auto f3 = bind(&C::fun, _1, _2);
    cout << f3(C(), 4) << endl;

    auto f4 = bind(C(), _1, _2);
    cout << f4(2, 2) << endl;
}

输出:

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/562524.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-01
下一篇 2022-04-01

发表评论

登录后才能评论

评论列表(0条)

保存