of c 2b 2b bind class member function

Solutions on MaxInterview for of c 2b 2b bind class member function by the best coders in the world

showing results for - "of c 2b 2b bind class member function"
Lina
16 Jan 2020
1// bind example
2#include <iostream>     // std::cout
3#include <functional>   // std::bind
4
5// a function: (also works with function object: std::divides<double> my_divide;)
6double my_divide (double x, double y) {return x/y;}
7
8struct MyPair {
9  double a,b;
10  double multiply() {return a*b;}
11};
12
13int main () {
14  using namespace std::placeholders;    // adds visibility of _1, _2, _3,...
15
16  // binding functions:
17  auto fn_five = std::bind (my_divide,10,2);               // returns 10/2
18  std::cout << fn_five() << '\n';                          // 5
19
20  auto fn_half = std::bind (my_divide,_1,2);               // returns x/2
21  std::cout << fn_half(10) << '\n';                        // 5
22
23  auto fn_invert = std::bind (my_divide,_2,_1);            // returns y/x
24  std::cout << fn_invert(10,2) << '\n';                    // 0.2
25
26  auto fn_rounding = std::bind<int> (my_divide,_1,_2);     // returns int(x/y)
27  std::cout << fn_rounding(10,3) << '\n';                  // 3
28
29  MyPair ten_two {10,2};
30
31  // binding members:
32  auto bound_member_fn = std::bind (&MyPair::multiply,_1); // returns x.multiply()
33  std::cout << bound_member_fn(ten_two) << '\n';           // 20
34
35  auto bound_member_data = std::bind (&MyPair::a,ten_two); // returns ten_two.a
36  std::cout << bound_member_data() << '\n';                // 10
37
38  return 0;
39}