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
:
invocation.cpp
:
#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;
}