函数模板绑定为f生成转发调用包装器.调用这个包装器等同于调用f,其中一些参数绑定到args.
#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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用bind来操作现有函数的参数顺序或修复一些参数.这在stl容器和算法中特别有用,您可以在其中传递其签名与您的需求匹配的现有库函数.
例如,如果您想将容器中的所有双打转换为2,那么您可以执行以下操作:
std::transform(begin(dbl_vec),
end(dbl_vec),
begin(dbl_vec),
std::bind(std::pow, _1, 2));
Run Code Online (Sandbox Code Playgroud)