What is a forwarding (universal) reference and how is it deduced?
Short answer
A forwarding reference is a function template parameter of the form T&& where T is deduced. It binds to both lvalues and rvalues: for an lvalue argument T deduces to U& (reference collapsing makes the param U&), and for an rvalue T deduces to U (param U&&).
Advertisement
AModel answer
A forwarding reference is a function template parameter of the form T&& where T is deduced. It binds to both lvalues and rvalues: for an lvalue argument T deduces to U& (reference collapsing makes the param U&), and for an rvalue T deduces to U (param U&&). Combined with std::forward, it enables perfect forwarding of value category.
template <class T>
void wrapper(T&& x) { inner(std::forward<T>(x)); }Real-world example
A factory forwards its arguments to a constructor preserving whether each was an lvalue or rvalue.
Likely follow-ups
- What is reference collapsing? | Why pair it with std::forward?
Related topics