函数绑定的目的 [英] The purpose of Function Binding

查看:97
本文介绍了函数绑定的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习asio编程的c ++ Boost库。我遇到了许多使用函数bind()的例子,它有函数指针作为参数。

I am learning asio programming of c++ Boost library. And I have encountered many examples that use the function bind() which has function pointer as argument.

我还不能理解bind()函数的使用。这就是为什么我有困难使用asio的boost库理解程序。

I have not been able to understand the use of bind() function. And that's why I have difficulty in understanding programs using asio of boost library.

我不是在这里寻找任何代码。我只是想知道使用bind()函数或其任何等效函数。
提前感谢。

I am not seeking for any code here. I just want to know the use of bind() function or any of its equivalent function. Thanks in advance.

推荐答案

cppreference


函数模板绑定生成转发调用包装器f。
调用这个包装器相当于调用f并将一些
参数绑定到args。

The function template bind generates a forwarding call wrapper for f. Calling this wrapper is equivalent to invoking f with some of its arguments bound to args.

下面的示例演示bind

#include <iostream>
#include <functional>

 using namespace std;

int my_f(int a, int b)
{
    return 2 * a + b;
}

int main()
{
    using namespace std::placeholders;  // for _1, _2, _3...

     // Invert the order of arguments
     auto my_f_inv = bind(my_f, _2, _1);        // 2 args b and a
    // Fix first argument as 10
    auto my_f_1_10 = bind(my_f, 10, _1);        // 1 arg b
    // Fix second argument as 10
    auto my_f_2_10 = bind(my_f, _1, 10);        // 1 arg a
    // Fix both arguments as 10
    auto my_f_both_10 = bind(my_f, 10, 10);     // no args

    cout << my_f(5, 15) << endl; // expect 25
    cout << my_f_inv(5, 15) << endl; // expect 35
    cout << my_f_1_10(5) << endl; // expect 25
    cout << my_f_2_10(5) << endl; // expect 20
    cout << my_f_both_10() << endl; // expect 30

    return 0;
}

您可以使用bind来操作现有函数的参数顺序, 。这可以在stl容器和算法中特别有用,您可以传递其签名与您的需求匹配的现有库函数。

You can use bind to manipulate an existing function's argument order, or fix some arguments. This can be particularly helpful in stl container and algorithms where you can pass an existing library library function whose signature matches with your requirement.

例如,如果您想将所有在你的容器中加倍2,你可以简单地通过做 std :: transform(begin(dbl_vec),end(dbl_vec),begin(dbl_vec),std :: bind ,_1,2))

For example if you want to transform all your doubles in your container to power 2, you can simply pass do something like std::transform(begin(dbl_vec), end(dbl_vec), begin(dbl_vec), std::bind(std::pow, _1, 2))

Live示例

这篇关于函数绑定的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆