cpp / expert
Snippet
Perfect Forwarding with std::forward
Perfect forwarding ensures that a function template can pass its arguments to another function while preserving their original value category (lvalue or rvalue). This is achieved using universal references (T&&) and std::forward.
snippet.cpp
1
2
3
4
5
6
7
template <typename T>void wrapper(T&& arg) {target(std::forward<T>(arg));}// target(int&); // Lvalue// target(int&&); // Rvalue
Breakdown
1
T&& arg
A forward reference (universal reference) that can bind to both lvalues and rvalues.
2
std::forward<T>(arg)
Conditionally casts the argument to an rvalue only if it was originally passed as an rvalue.