functional 和 bind 用法

时间:2022-07-26
本文章向大家介绍functional 和 bind 用法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用 functional 和 bind 就可以简单绑定类成员函数参数,且能指定对象。

成员函数必须用 & 来获取地址,非成员就不需要,方便记,就统一加 & 好了。

#include <iostream>
#include <functional>

using namespace std;
using namespace std::placeholders;

typedef function<void()> TestCallback;
typedef function<void(int)> TestCallback2;

class funClass {
public:
    void fun(int  a) {
        cout << a << endl;
    }
};

void notClassNumber(int a) {
    cout << a << endl;
}

void TestCall(TestCallback cb) {
    cb();
}

void TestCall2(TestCallback2 cb) {
    cb(45);
}

int main() {
    funClass f;

    // 调用绑定,成员函数的,就 bind( 函数名,对象指针,args...);
    TestCallback cb1 = bind(&funClass::fun, &f, 10);
    TestCall(cb1);

    // 对于非成员函数的,就 bind( 函数名,args...);
    TestCallback cb2 = bind(&notClassNumber, 20);
    TestCall(cb2);

    // 对于参数不绑定的
    TestCallback2 cb3 = bind(&notClassNumber, _1);
    TestCall2(cb3);
    system("pause");
    return 0;
}