what is the difference between forward<T>(a) and (T&&)(a)

c++, c++11

Solution

There is no practical difference. `std::forward<T>(v)` is specified as `static_cast<T&&>(v)`.

`§20.2.3 [forward]`

template <class T> T&& forward(typename remove_reference<T>::type& t) noexcept;
template <class T> T&& forward(typename remove_reference<T>::type&& t) noexcept;

2 Returns: `static_cast<T&&>(t)`.

A C-style cast goes through most C++-style casts to determine the first working one. One of them is `static_cast`, which also is the first one that works in this case.

`§5.4 [expr.cast] p4`

The conversions performed by

- a `const_cast` (5.2.11),

- a `static_cast` (5.2.9),

- a `static_cast` followed by a `const_cast`,

- a `reinterpret_cast` (5.2.10), or

- a `reinterpret_cast` followed by a `const_cast`,

can be performed using the cast notation of explicit type conversion. [...] If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed.

I'd advise to stick with `std::forward`, though. The intent is clear from the name and and people will know what it does much more likely than knowing what a weird `static_cast<T&&>` (or even `(T&&)`) does.

Problem

``` template<typename T> void outer(T&& t) {inner(forward<T>(t));} template<typename T> void outer(T&& t) {inner((T&&)(t));} ``` what is the difference?

Original source