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
#include <iostream>
#include <functional>
#include <vector>
struct A
{
// **** note: modified to take an int argument
void do_some_thing( long arg ) const
{ std::cout << "A::do_something(" << arg << ")\n" ; }
};
struct B
{
int do_some_thing_else( int v )
{
std::cout << "B::do_something_else(" << v << ")\n" ;
return i += v ;
}
int i = 0 ;
};
void do_a_third_thing( int v ) { std::cout << "::do_a_third_thing(" << v << ")\n" ; }
struct to_do_list
{
// https://en.cppreference.com/w/cpp/utility/functional/bind
// **** note: we use a placeholder for the int argument to be passed later
template < typename FN, typename... ARGS > void add( FN fn, ARGS&&... args )
{ things_to_be_done.emplace_back( std::bind( fn, std::forward<ARGS>(args)..., std::placeholders::_1 ) ) ; }
void do_them_now( int with_this_arg ) // *** note: call the functions with_this_arg
{
int cnt = 0 ;
for( const auto& fn : things_to_be_done )
{
std::cout << ++cnt << ". " ;
fn(with_this_arg) ; // *** call passing with_this_arg as the argument
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
echo && echo && g++ -std=c++17 -O3 -Wall -Wextra -pedantic-errors -pthread -march=native main.cpp && ./a.out
echo && echo && clang++ -std=c++17 -O3 -Wall -Wextra -pedantic-errors -pthread -march=native main.cpp -lsupc++ && ./a.out



call functions with arg == 25
----------------
1. A::do_something(25)
2. B::do_something_else(25)
3. ::do_a_third_thing(25)
4. closure: do this too arg == 25

call functions with arg == 99
----------------
1. A::do_something(99)
2. B::do_something_else(99)
3. ::do_a_third_thing(99)
4. closure: do this too arg == 99

call functions with arg == -7
----------------
1. A::do_something(-7)
2. B::do_something_else(-7)
3. ::do_a_third_thing(-7)
4. closure: do this too arg == -7



call functions with arg == 25
----------------
1. A::do_something(25)
2. B::do_something_else(25)
3. ::do_a_third_thing(25)
4. closure: do this too arg == 25

call functions with arg == 99
----------------
1. A::do_something(99)
2. B::do_something_else(99)
3. ::do_a_third_thing(99)
4. closure: do this too arg == 99

call functions with arg == -7
----------------
1. A::do_something(-7)
2. B::do_something_else(-7)
3. ::do_a_third_thing(-7)
4. closure: do this too arg == -7