c++ - 函数绑定(bind)的目的

标签 c++ boost bind

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

我一直无法理解 bind() 函数的用法。这就是为什么我很难理解使用 boost 库的 asio 的程序。

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

最佳答案

来自 cppreference

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.

检查 example below演示绑定(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 容器和算法中特别有用,您可以在其中传递其签名与您的要求匹配的现有库函数。

例如,如果您想将容器中的所有 double 转换为 2 的幂,您可以简单地执行以下操作:

std::transform(begin(dbl_vec),
               end(dbl_vec),
               begin(dbl_vec),
               std::bind(std::pow, _1, 2));

Live example here

关于c++ - 函数绑定(bind)的目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27314972/

相关文章:

c++ - C++ 中的多维容器

c++ - 在 boost::python 中公开 boost::scoped_ptr

c++ - Boost 构建系统未设置输出库名称的编译器版本标记

docker - 将目录绑定(bind)到 docker 容器

jquery 在 Firefox 中将 keyup 绑定(bind)到 body

c++ - 迭代器值与转换后的反向迭代器值不同

c++ - 延迟执行代码

javascript - promise 错误函数上的bind() - javascript

c++ - 按顺时针顺序排列坐标

c++ - boost multi_index 反向迭代器删除麻烦