std::bind示例一
代码
class A {
public:
void fun(int a, int b, int c) {
std::cout << "A::fun()" << std::endl;
std::cout << a << std::endl;
std::cout << b << std::endl;
std::cout << c << std::endl;
}
};
int main() {
A a;
using namespace std::placeholders;
std::function<void(int)> f1 = std::bind(&A::fun, a, _ 1, 99, 99);
std::function<void(int)> f2 = std::bind(&A::fun, a, 99, _ 1, 99);
std::function<void(int)> f3 = std::bind(&A::fun, a, 99, 99, _ 1);
std::function<void(int, int)> f4 = std::bind(&A::fun, a, 99, _ 1, _ 2);
f1(1);
f2(1);
f3(1);
f4(1, 2);
return system("pause");
}
输出结果
A::fun()
1
99
99
A::fun()
99
1
99
A::fun()
99
99
1
A::fun()
99
1
2
std::bind示例二
#include <iostream>
#include <functional>
// a function: (also works with function object: std::divides<double> my_divide;)
double my_divide(double x, double y) { return x / y; }
struct MyPair {
double a, b;
double multiply() { return a * b; }
};
int main() {
using namespace std::placeholders; // adds visibility of _ 1, _ 2, _ 3,...
// binding functions:
auto fn_five = std::bind(my_divide, 10, 2); // returns 10/2
std::cout << fn_five() << '\n'; // 5
auto fn_half = std::bind(my_divide, _ 1, 2); // returns x/2
std::cout << fn_half(10) << '\n'; // 5
auto fn_invert = std::bind(my_divide, _ 2, _ 1); // returns y/x
std::cout << fn_invert(10, 2) << '\n'; // 0.2
auto fn_rounding = std::bind<int>(my_divide, _ 1, _ 2); // returns int(x/y)
std::cout << fn_rounding(10, 3) << '\n'; // 3
MyPair ten_two{10, 2};
// binding members:
auto bound_member_fn = std::bind(&MyPair::multiply, _ 1); // returns x.multiply()
std::cout << bound_member_fn(ten_two) << '\n'; // 20
auto bound_member_data = std::bind(&MyPair::a, ten_two); // returns ten_two.a
std::cout << bound_member_data() << '\n'; // 10
return 0;
}
网友评论