Perfect Forwarding
std::forward and universal references
Interview Relevant: Advanced template programming
Perfect Forwarding
Forward arguments preserving their value category.
Code Examples
Perfect forwarding for generic code.
cpp
1// Universal reference (forwarding reference)
2template<typename T>
3void wrapper(T&& arg) {
4 // Forward preserves lvalue/rvalue nature
5 process(forward<T>(arg));
6}
7
8// Without forwarding
9void badWrapper(int& x) { process(x); } // Only lvalues
10void badWrapper(int&& x) { process(move(x)); } // Only rvalues
11// Need 2^n overloads for n parameters!
12
13// With perfect forwarding
14template<typename... Args>
15void perfectWrapper(Args&&... args) {
16 process(forward<Args>(args)...);
17}
18
19// Factory function example
20template<typename T, typename... Args>
21unique_ptr<T> make_unique(Args&&... args) {
22 return unique_ptr<T>(new T(forward<Args>(args)...));
23}
24
25// Called with lvalue or rvalue
26string s = "hello";
27perfectWrapper(s); // s forwarded as lvalue
28perfectWrapper(string("hi")); // Forwarded as rvalue