简体   繁体   中英

How do I create an efficient closure using C++11?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM