CKTIS / C++
Forwarding reference T&&
A forwarding reference T&& lets a template accept lvalues and rvalues while retaining the information needed to forward the argument onward. It requires the appropriate deduction context; && alone is not enough.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
template<class T>
void relay(T&& value);In template<class T> void relay(T&& value);, the parameter T&& is a forwarding reference (Forwarding reference T&&): it refers to a template parameter without added const or volatile qualifiers. When T is deduced from the call argument, the mechanism handles both lvalues and rvalues.
For an lvalue of type int, deduction produces T = int&, and reference collapsing turns T&& into int&. For an lvalue of type const int, the result is T = const int& and a const int& parameter. For an rvalue of type int, we get T = int and an int&& parameter. In reference collapsing, the presence of & produces &; only combining two && produces &&.
Not every && denotes a forwarding reference: const T&& and int&& do not. In template<class T> struct Box { void set(T&&); };, the parameter of set is not one either: T comes from the class template rather than deduction for the call to set. During class template argument deduction, an exclusion applies to parameters of that class template. Explicitly specifying relay<int>(x) also bypasses deduction of T and does not allow the lvalue x to bind to int&&.
In the example, the expression value is an lvalue even when the parameter type is int&&. std::forward<T>(value) forwards an lvalue as an lvalue and an rvalue as an xvalue, preserving type qualifiers. Plain inspect(value) would select an lvalue overload even after relay(42). std::move(value) unconditionally converts the expression to an xvalue, so it does not replace correct forwarding. Forwarding does not automatically extend an object's lifetime; do not retain a reference to a temporary beyond its lifetime.
Examples
#include <iostream>
#include <utility>
void inspect(int&) { std::cout << "lvalue\n"; }
void inspect(const int&) { std::cout << "const lvalue\n"; }
void inspect(int&&) { std::cout << "rvalue\n"; }
template<class T>
void relay(T&& value) {
inspect(std::forward<T>(value));
}
int main() {
int x = 7;
const int cx = 9;
relay(x);
relay(cx);
relay(42);
}
Result
lvalue const lvalue rvalue
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.