为什么decltype用于尾随返回类型?

Sun*_*hah 6 c++ decltype auto c++11 return-type-deduction

请考虑以下代码:

template< class T1 , class T2>
auto calc( T1 a , T2 b )
{
   return a + b ;
}


template< class T1 , class T2>
auto calc( T1 a , T2 b ) -> decltype( a + b )
{
   return a + b ;
}
Run Code Online (Sandbox Code Playgroud)

什么是第二个代码的差异?你能举一些例子说明这会产生什么影响,还是会有所不同?

Tem*_*Rex 7

请注意,普通auto返回类型仅适用于C++ 14,而尾随返回类型decltype适用于C++ 11.引用进入图片时会出现差异,例如代码如下:

#include <type_traits>

struct Test
{
    int& data;

    auto calc1()
    {
       return data;
    }

    auto calc2() -> decltype(data)
    {
       return data;
    }
};

int main()
{
    int x;
    Test t{x};
    static_assert(std::is_same<int, decltype(t.calc1())>::value, "");
    static_assert(std::is_same<int&, decltype(t.calc2())>::value, "");
}
Run Code Online (Sandbox Code Playgroud)

如果要删除->decltype()并保持代码的行为相同,可以使用C++ 14结构decltype(auto)

decltype(auto) calc3() // same as calc2() above
{
    return data;
}
Run Code Online (Sandbox Code Playgroud)

它也保留了返回类型的参考性.

如果您已经知道您的返回类型是引用,那么只需将其显式化即可

auto& calc4() // same as calc2() above
{
    return data;
}
Run Code Online (Sandbox Code Playgroud)