Function Binding in C++

Level 5433 keystrokes

A function<int(int, int)> can hold any callable with that signature. Here it first holds a member function bound to an object with bind, then a plain function, and each is called the same way.

C++ code

// Class with two member functions
1class Calculator {
2public:
3 int add(int a, int b) { return a + b; }
4 int multiply(int a, int b) { return a * b; }
5};
6
// Plain function: base raised to the power exp
7int power(int base, int exp) {
8 int result = 1;
// Multiplies by base exp times
9 for (int i = 0; i < exp; i++) result *= base;
10 return result;
11}
12
// Object whose member function will be bound
13Calculator calc;
// Can hold any callable that takes two ints and returns an int
14function<int(int, int)> op;
15
// bind fixes the object (&calc); _1 and _2 are filled with the call's arguments
16op = bind(&Calculator::add, &calc, placeholders::_1, placeholders::_2);
// Calls calc.add(5, 3): prints "Add: 8"
17cout << "Add: " << op(5, 3) << endl;
18
// The same variable can now hold a plain function
19op = power;
// 2 to the 8th power: prints "Power: 256"
20cout << "Power: " << op(2, 8) << endl;

Output

Add: 8
Power: 256
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • ;× 14
  • <× 14
  • ,× 9
  • :× 9
  • (× 8
  • )× 8
  • =× 5
  • "× 4
  • {× 4
  • }× 4

More C++ examples at level 5

← C++ typing practice