我正在学习 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));
关于c++ - 函数绑定(bind)的目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27314972/