Search code examples
c++stdforward

std::forward description, which one is correct?


I was looking for std::forward and found two links whose description could be interpreted differently.

cplusplus.com: Returns an rvalue reference to arg if arg is not an lvalue reference.

cppreference.com: Forwards lvalues as either lvalues or as rvalues, depending on T

The difference is the reference I think.

Can you tell me which is the correct explanation? Thanks.

found descriptions and compare


Solution

  • cppreference is correct, and cplusplus is wrong


    from the standard §forward

    template<class T> constexpr T&& forward(remove_reference_t<T>& t) noexcept;
    template<class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept;
    
    • Mandates: For the second overload, is_­lvalue_­reference_­v<T> is false.
    • Returns: static_­cast<T&&>(t).

    notes

    • the function always accept reference and returns reference.
    • the template parameter T is always specify explicitly, it's never deduced from the function parameter t (or arg)

    from cplusplus

    Returns an rvalue reference to arg if arg is not an lvalue reference.

    If arg is an lvalue reference, the function returns arg without modifying its type.

    this is incorrect

    • the rvalue (first) overload should result in error if T is lvalue reference type
    • the lvalue (second) overload should return rvalue if T is rvalue (reference type)

    from cppreference

    template< class T >
    constexpr T&& forward( std::remove_reference_t<T>& t ) noexcept;
    

    Forwards lvalues as either lvalues or as rvalues, depending on T


    template< class T >
    constexpr T&& forward( std::remove_reference_t<T>& t ) noexcept;
    

    Forwards rvalues as rvalues and prohibits forwarding of rvalues as lvalues

    this is correct.