std::forward
Use case
Preserve lvalue/rvalue when passing arguments through a wrapper.
Explanation
std::forward<T>(arg) preserves the original value category. Without it, arg would always be treated as an lvalue (it has a name). Use it in templates that pass arguments to other functions.
Code
#include <iostream>
#include <string>
#include <utility>
void process(const std::string &s) { std::cout << "lvalue: " << s << "\n"; }
void process(std::string &&s) { std::cout << "rvalue: " << s << "\n"; }
template <typename T> void wrapper(T &&arg) { process(std::forward<T>(arg)); }
int main() {
std::string name = "_main";
// lvalue.
wrapper(name);
// rvalue.
wrapper(std::string("_helper"));
return 0;
}
Output
$ ./src/c++11/build/std-forward
lvalue: _main
rvalue: _helper