1 #include <iostream>
2 #include <functional>
3 #include <string>
4 void printTemperature(std::string& name, int daySeq, float temperature) {
5 std::cout<< "name: " << name << std::endl;
6 std::cout<< "daySeq: " << daySeq << std::endl;
7 std::cout<< "temperature: " << temperature << std::endl;
8 }
9
10 class Car {
11 public:
12 Car() : m_Color("red") {
13
14 }
15 void print() {
16 std::cout << m_Color << std::endl;
17 }
18 std::string m_Color;
19 };
20
21 int main()
22 {
23 // 去掉默认参数,std::placeholders::_2 表示printTemperature的第三个参数放在bindFunc1的第二个位置
24 std::string name = "A";
25 std::function<void(std::string&, float)> bindFunc1 = std::bind(printTemperature, std::placeholders::_1, 1, std::placeholders::_2);
26 bindFunc1(name, 100.1);
27 std::cout << "=================================" << std::endl;
28
29 // 调整参数顺序
30 name = "B";
31 std::function<void(float,std::string&, int)> bindFunc2 = std::bind(printTemperature, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);
32 bindFunc2(3000.0, name, 2);
33
34 // 调整参数顺序 和 去掉默认参数
35 name = "C";
36 std::function<void(int, std::string&)> bindFunc3 = std::bind(printTemperature, std::placeholders::_2, std::placeholders::_1, 100.1);
37 bindFunc3(10, name);
38 std::cout << "=================================" << std::endl;
39
40 Car car;
41 // 需要显示获取成员函数的地址,因为编译器不会将对象的成员函数隐式转换为函数指针, &Car::print
42 std::function<void(void)>bindClassFunc = std::bind(&Car::print, &car);
43 bindClassFunc();
44 return 0;
45 }