C++ Universal (Forwarding) References Explained

C++ Universal (Forwarding) References Explained

이 글의 핵심

Identify forwarding references in template code and preserve value categories with std::forward.

What is a universal reference?

Scott Meyers’ term: in template<typename T> void f(T&& x), T&& can bind to lvalues and rvalues because of deduction plus reference collapsing.

template<typename T>
void func(T&& arg) {}

int x = 10;
func(x);              // T = int&
func(10);             // T = int
func(std::move(x));   // T = int

Not universal references

void g(int&&);                    // rvalue only

template<typename T>
struct W { void h(T&&); };        // T is fixed per specialization—not deduced per call like free `T&&`

std::forward

template<typename T>
void wrapper(T&& arg) {
    callee(std::forward<T>(arg));
}

auto&& in range-for

for (auto&& item : container) {
    // binds to either lvalues or rvalues of elements
}

const T&&

This is not a forwarding reference—it binds to rvalues only.


  • Reference collapsing
  • Perfect forwarding

Keywords

C++, forwarding reference, universal reference, std::forward, templates