Perfect Forwarding
This lesson explains the principle of perfect forwarding.
A classic problem: A function wants to get its arguments by reference.
Press + to interact
struct BigData{BigData(vector<int>& d): data(d){} // Lvalue-RefBigData(const vector<int>& d): data(d){} ... // const Lvalue-Ref};struct BigData2{template<typename T>BigData2(T&& d): data(std::forward<T>(d)){} // Lvalue- and Rvalue-Ref};
For n parameters, 2n function overloads are necessary.
Definition #
If a function template forwards its arguments without changing their lvalue or rvalue characteristics, we call it perfect forwarding.
A perfect factory method #
First, a short disclaimer; the expression, perfect factory method, is not a formal term.
A perfect factory method is a totally generic factory method. In particular, it implies that the function should have the following characteristics:
- takes an arbitrary number of arguments.
- accepts lvalues and rvalues as arguments.
- forwards its arguments in the same way as the underlying constructor.
Let’s describe this in a more formal way. A perfect factory method should be able to create each arbitrary object. ...