C++11: Perfect forwarding

Consider this function template invoke that invokes the function/functor/lambda expression passed as argument passing it the two extra arguments given:

#include <iostream>
#include <string>

using namespace std;

void sum(int a, int b)
{
    cout << a + b << endl;
}

void concat(const string& a, const string& b)
{
    cout << a + b << endl;
}

template <typename PROC, typename A, typename B>
void invoke(PROC p, const A& a, const B& b)
{
    p(a, b);
}

int main()
{
    invoke(sum, 10, 20);
    invoke(concat, "Hello ", "world");
    return 0;
}

Nice, it works as expected and the result is:

30
Hello world

Continue reading “C++11: Perfect forwarding”

Advertisement