bind.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <functional>

void print(int a, int b, int c) {
    std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
}

void test1()
{
    auto printReordered = std::bind(print, std::placeholders::_2, std::placeholders::_1, std::placeholders::_3);
	std::cout << "arguments to printReordered: 20, 30, 40" << std::endl;
    std::cout << "placeholders: 2, 1, 3" << std::endl;
    printReordered(20, 30, 40);  // Outputs: a = 30, b = 20, c = 40
}

void test2()
{
    auto printReordered = std::bind(print, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);
	std::cout << "arguments to printReordered: 20, 30, 40" << std::endl;
    std::cout << "placeholders: 2, 3, 1" << std::endl;
    printReordered(20, 30, 40);  // Outputs: a = 30, b = 40, c = 20
}

void test3()
{
    auto printReordered = std::bind(print, std::placeholders::_3, std::placeholders::_1, std::placeholders::_2);
	std::cout << "arguments to printReordered: 20, 30, 40" << std::endl;
	//std::cout << "arguments to print: 30, 40, 20" << std::endl;
    std::cout << "placeholders: 3, 1, 2" << std::endl;
    printReordered(20, 30, 40);  // Outputs: a = 40, b = 20, c = 30
}

int main() {
    // Bind the first argument to 10, and reorder the rest
    //auto printReordered = std::bind(print, std::placeholders::_3, std::placeholders::_1, std::placeholders::_2);

	std::cout << "------------------------------------" << std::endl;
	test1();
	std::cout << "------------------------------------" << std::endl;
	test2();
	std::cout << "------------------------------------" << std::endl;
	test3();

    return 0;
}
Back to std_function