Perfect Forwarding

If a function template forwards its arguments without changing their lvalue or rvalue characteristics, we call it perfect forwarding.

A Perfect Factory Method

Firstly, a short disclaimer: the expression a perfect factory method is not a formal term.

A perfect factory method is actually a generic factory method, meaning that the function should have the following characteristics:

  • It can take an arbitrary number of arguments
  • It can accept lvalues and rvalues as an argument
  • It forwards it arguments identical to the underlying constructor

In other words, a perfect factory method should be able to create each arbitrary object.

Perfect forwarding enables it to write a function that can identically forward its arguments. In doing so, the lvalue and rvalue properties are respected.

Let’s start with the first iteration and move towards implementing the perfect factory method.

First Iteration

For efficiency reasons, the function template should take its arguments by reference. To say it exactly, it should take it as a non-constant lvalue reference. The following is the function template create in our first iteration.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy