CKTIS / C++
std::forward: preserving a value category
std::forward<T> restores the value category recorded by forwarding-reference deduction.
Version: C++23
Syntax
template<class T>
constexpr T&& std::forward(std::remove_reference_t<T>& t) noexcept;
template<class T>
constexpr T&& std::forward(std::remove_reference_t<T>&& t) noexcept;std::forward<T>(t) from <utility> returns static_cast<T&&>(t) and is constexpr and noexcept. In a relay, a named T&& parameter is itself an lvalue. If the argument was an lvalue, T is deduced as U& and reference collapsing yields U&; for an rvalue, T is U and the result is U&&.
The example relays its parameter to two select overloads. A named int selects select(int&), while a temporary selects select(int&&), so it prints lvalue rvalue. Perfect forwarding also preserves cv-qualification such as const.
std::forward does not move an object or extend its lifetime; it casts, after which the receiver may move. Use the exact deduced T and normally forward a potentially consumed value once. An explicitly wrong type can turn an lvalue into an rvalue. The second overload mandates that T is not an lvalue reference, so that form cannot forward an rvalue as an lvalue.
Examples
#include <iostream>
#include <utility>
void select(int&) { std::cout << "lvalue "; }
void select(int&&) { std::cout << "rvalue\n"; }
template<class T>
void relay(T&& value) {
select(std::forward<T>(value));
}
int main() {
int value = 1;
relay(value);
relay(2);
}
Result
lvalue rvalue
std::forward → lvalue rvalue