C++ Perfect forwarding.

Xiahua Liu August 28, 2024 #C++

Perfect forwarding comes from std::forward() is one of the special C++ technique to reduce the code length.

More information can be found on cppreference.com.

How it works

Basically it forwards a rvalue reference to the nested function inside a function template.

template<class T>
void wrapper(T&& arg)
{
    // arg is always lvalue
    foo(std::forward<T>(arg)); // Forward as lvalue or as rvalue, depending on T
}

For both cases, foo(), which takes an rvalue parameter OR lvalue reference, will work correctly.

Difference from std::move()

The difference from std::move() is that, std::forward<T>() is conventionally used in function template only.

You can think std::forward<T>() is a smarter version of std::move(), however it requires a typename to work.