mario::konrad
programming / C++ / sailing / nerd stuff
Function Invocation using Variadic Templates
© 2013 / Mario Konrad

Deferred invokation of functions (with and without parameters). Of course you'll need a C++11 capable compiler. This example is tested with gcc 4.8.1:

$ g++ -Wall -Wextra -std=c++11 -o invocation invocation.cpp
$ ./invocation

invocation.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
46
47
48
49
50
51
#include <utility>
#include <functional>
#include <iostream>

using namespace std;

// invoke specified function using the given parameters.
template <typename ... Args>
inline void invoke(function<void(Args ...)> func, Args&& ... args)
{
    func(forward<Args>(args) ...);
}

// invoke specified function using the given parameters. wrapps
// the function pointer to  a std::function.
template <typename ... Args>
inline void invoke(void (*func)(Args ...), Args&& ... args)
{
    invoke(function<void(Args ...)>(func), forward<Args>(args) ...);
}


void f0()
{
    cout << __PRETTY_FUNCTION__ << endl;
}

void f1(int a)
{
    cout << __PRETTY_FUNCTION__ << ": a=" << a << endl;
}

void f2(int a, int b)
{
    cout << __PRETTY_FUNCTION__ << ": a=" << a << " b=" << b << endl;
}

int main(int, char**)
{
    // without wrapper
    invoke(function<void()>(f0));
    invoke(function<void(int)>(f1), 10);
    invoke(function<void(int, int)>(f2), 20, 30);

    // with wrapper
    invoke(f0);
    invoke(f1, 10);
    invoke(f2, 20, 30);

    return 0;
}