Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ decltype(auto) or decltype(std::forward<T>(value))?

For example, simple identity functor:

template <typename T>
class identity
{
public:
    constexpr auto operator ()(T && i) -> decltype(std::forward<T>(i))
    {
        return std::forward<T>(i);
    }
};

What is better (C++14 and newer) for return value:

  • -> decltype(std::forward<T>(i)) or
  • -> decltype(auto)

Or are they the same?

like image 371
vladon Avatar asked Dec 20 '17 13:12

vladon


1 Answers

Or are they the same?

Assuming you write it correctly:

constexpr decltype(auto) operator ()(T && i)
{
    return std::forward<T>(i);
}

They are the same. [dcl.type.auto.deduct]:

A type T containing a placeholder type, and a corresponding initializer e, are determined as follows:

  • for a non-discarded return statement that occurs in a function declared with a return type that contains a placeholder type, T is the declared return type and e is the operand of the return statement. If the return statement has no operand, then e is void();

If the placeholder is the decltype(auto) type-specifier, T shall be the placeholder alone. The type deduced for T is determined as described in [dcl.type.simple], as though e had been the operand of the decltype

The return type of the function is deduced from return e; as though by decltype(e). So it would be the same as an explicit decltype(std::forward<T>(i)).

What is better

In this case, I'll go with "less is more". decltype(auto) gives you what you are after with less verbosity.

like image 140
StoryTeller - Unslander Monica Avatar answered Sep 29 '22 13:09

StoryTeller - Unslander Monica