Question

I'm trying to capture the parameters passed to a function in a closure-like object. The main goal is to capture (store a reference not a copy) parameters of any type. (Here's why.)

Here's a very simplified version that only captures 2 parameters and stores them in a pair:

template<typename T1, typename T2>
void foo(T1&& t1, T2&& t2)
{
    pair<T1&&, T2&&> p(forward(t1), forward(t2)); // Capture parameters -- doesn't work
    cout << p.first << "," << p.second << endl;
}

int main()
{
    string s = "hey";
    foo("hello", "world");
    foo(1, 2);
    foo(s, endl);
    return 0;
}

Unfortunately this doesn't compile with g++ 4.7.2:

main.cpp: In instantiation of 'void foo(T1&&, T2&&) [with T1 = basic_string<char>&; T2 = basic_string<char>&]':
main.cpp: error: no matching function for call to 'forward(basic_string<char>&)'
...

How do I declare and initialize p to make the above compile?

Was it helpful?

Solution

You have to specify an explicit type for std::forward

pair<T1&&, T2&&> p(forward<T1>(t1), forward<T2>(t2));

The compiler won't be able to figure out the types of endl either if you want to use it like that, so they must be specified too endl<char, char_traits<char>>, you should probably be using '\n' anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top