c++中bind函数如何使用

发布时间:2021-06-23 14:32:59 作者:Leah
来源:亿速云 阅读:159

这篇文章给大家介绍c++中bind函数如何使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

bind函数:

  auto newCallable = bind(callable, arg_list);

  callable依据手册可以是:

  Callable object (function object, pointer to function, reference to function, pointer to member function, or pointer to data member) that will be bound to some arguments.

bind函数简述: 

  bind函数看做一个通用的函数适配器,它接受一个可调用对象callable,生成一个新的可调用对象newCallable。

  它可以把原可调用对象callable的某些参数预先绑定到给定的变量中(也叫参数绑定),然后产生一个新的可调用对象newCallable。

网络编程中, 经常要使用到回调函数。 当底层的网络框架有数据过来时,往往通过回调函数来通知业务层。 这样可以使网络层只专注于 数据的收发, 而不必关心业务

在c语言中, 回调函数的实现往往通过函数指针来实现。 但是在c++中 , 如果回调函数是一个类的成员函数。这时想把成员函数设置给一个回调函数指针往往是不行的

因为类的成员函数,多了一个隐含的参数this。 所以直接赋值给函数指针肯定会引起编译报错。

bind函数用法:

一、普通函数

#include <iostream>#include <memory>#include <functional>using namespace std::placeholders;using namespace std;void fun1(int n1, int n2, int n3)
{
    cout << n1 << " " << n2 << " " << n3 << endl;
}int main()
{//原fun1接受三个参数,其中绑定了2个,第三个参数由新的可调用对象指定  auto f1 = bind(fun1, 11, 22, _1); 
    f1(33);                                                                                                                                  
}

二、普通函数与_1、_2

#include <iostream>#include <memory>#include <functional>using namespace std::placeholders;using namespace std;void fun1(int n1, int n2, int n3)
{
    cout << n1 << " " << n2 << " " << n3 << endl;
}int main()
{//_1表示这个位置是新的可调用对象的第一个参数的位置//_2表示这个位置是新的可调用对象的第二个参数的位置  auto f1 = bind(fun1, _2, 22, _1);
    f1(44,55);
}

三、成员函数

#include <iostream>#include <memory>#include <functional>using namespace std::placeholders;using namespace std;class A
{public:void print(int n1, int n2, int n3)
    {
        cout << n1 << " " << n2 << " " << n3 << endl;
    }
};int main()                                                                                                                                   
{
    A a;//类成员函数需要绑定该类的this指针  auto f1 = bind(&A::print, &a, _2, 22, _1);
    f1(44,55);
}

关于c++中bind函数如何使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. C++ bind函数适配器
  2. javascript中bind函数的使用方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++ bind

上一篇:numpy中np.finfo如何使用

下一篇:spring boot中@ControllerAdvice的用法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》