decltype and auto parameters?

This question came up on a test in class last week, and for the life of me I wasn't able to figure it out then, as I'm still fuzzy with it now after having some time to Google.

 
why is it best to use decltype on auto&& parameters to std::forward them?


What does an example code snippet look like for this?

Thank you!
This response assumes you understand something about perfect forwarding. If not, read this well-known post (and/or ask):
http://thbecker.net/articles/rvalue_references/section_01.html

We usually see perfect forwarding in function templates:
1
2
3
template <typename T>
auto wrapper(T&& t) 
{ return f(std::forward<T>(t)); }

In which t is a forwarding reference (because the type T reflects the value category of the argument to wrapper).

Parameters declared as auto&& are (also) forwarding references, because auto uses the same deduction rules as function templates:
 
auto wrapper = [](auto&& t) { return f(std::forward<decltype(t)>(t)); };

We have to use decltype to get the type of t.
Last edited on
Topic archived. No new replies allowed.