Perfect forwarding explained

It means that a function template can pass its arguments through to another function whilst retaining the lvalue/rvalue nature of the function arguments by using std::forward. This is called “perfect forwarding”, avoids excessive copying, and avoids the template author having to write multiple overloads for lvalue and rvalue references.

Problem

Basically, given the expression E(a, b, … , c), we want the expression f(a, b, … , c) to be equivalent. In C++03, this is impossible. There are many attempts, but they all fail in some regard.

Perfect Forwarding: The Solution

You cannot forward something more than once, though, because that makes no sense. Forwarding means that you’re potentially moving the argument all the way through to the final caller, and once it’s moved it’s gone, so you cannot then use it again.

Written on December 10, 2017, Last update on March 21, 2020
c++