功能绑定的目的 [英] The purpose of Function Binding
问题描述
我学习C的ASIO ++编程Boost库。我也遇到了使用功能绑定(),它具有函数指针作为参数的例子很多。
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()函数的。这就是为什么我在理解使用boost库ASIO方案的难度。
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.
我不求任何code在这里。我只是想知道用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.
推荐答案
函数模板生成绑定在f转发呼叫包装。
调用此包装等同于某些援引˚F其
参数绑定成参数。
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.
检查展示结合下面的例如
Check the example below demonstrating 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;
}
您可以使用绑定操作现有的函数的参数顺序,或修复一些参数。这在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 ::变换(开始(dbl_vec),端(dbl_vec),开始( dbl_vec)的std ::绑定(性病::战俘,_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))
这里活生生的例子。
这篇关于功能绑定的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!