怎么使用std::bind

https://blog.csdn.net/u013654125/article/details/100140328
https://www.jianshu.com/p/f191e88dcc80
std::bind将可调用对象与其参数一起进行绑定,绑定后的结果可以使用std::function保存。
std::bind主要有以下两个作用:
1.将可调用对象和其参数绑定成一个防函数;
2.只绑定部分参数,减少可调用对象传入的参数。

《C++11中的std::function》中那段代码,std::function可以绑定全局函数,静态函数,但是绑定类的成员函数时,必须要借助std::bind的帮忙。但是话又说回来,不借助std::bind也是可以完成的,只需要传一个*this变量进去就好了,比如:

 
#include <iostream>
#include <functional>
using namespace std;
 
class View
{
public:
    void onClick(int x, int y)
    {
        cout << "X : " << x << ", Y : " << y << endl;
    }
};
 
// 定义function类型, 三个参数
function<void(View, int, int)> clickCallback;
 
int main(int argc, const char * argv[])
{
    View button;
 
    // 指向成员函数
    clickCallback = &View::onClick;
 
    // 进行调用
    clickCallback(button, 10, 123);
    return 0;
}

再来一段示例谈谈怎么使用std::bind代码:

#include <iostream>
#include <functional>
using namespace std;
 
int TestFunc(int a, char c, float f)
{
    cout << a << endl;
    cout << c << endl;
    cout << f << endl;
 
    return a;
}
 
int main()
{
    auto bindFunc1 = bind(TestFunc, std::placeholders::_1, 'A', 100.1);
    bindFunc1(10);
 
    cout << "=================================\n";
 
    auto bindFunc2 = bind(TestFunc, std::placeholders::_2, std::placeholders::_1, 100.1);
    bindFunc2('B', 10);
 
    cout << "=================================\n";
 
    auto bindFunc3 = bind(TestFunc, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);
    bindFunc3(100.1, 30, 'C');
 
    return 0;
}

std::placeholders是一个占位符。当使用bind生成一个新的可调用对象时,std::placeholders表示新的可调用对象的第 几个参数和原函数的第几个参数进行匹配,这么说有点绕。比如:

auto bindFunc3 = bind(TestFunc, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);
 
bindFunc3(100.1, 30, 'C');

可以看到,在bind的时候,第一个位置是TestFunc,除了这个,参数的第一个位置为占位符std::placeholders::_2,这就表示,调用bindFunc3的时候,它的第二个参数和TestFunc的第一个参数匹配,以此类推。
在这里插入图片描述在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42054167/article/details/106108887