为什么在尾随返回类型中使用decltype

Why decltype is used in trailing return types?

本文关键字:decltype 返回类型 为什么      更新时间:2023-10-16

考虑以下代码:

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 ;
}

第二段代码有什么不同?

你能举几个例子说明这有什么不同吗?

请注意,普通的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, "");
}

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

decltype(auto) calc3() // same as calc2() above
{
    return data;
}

,它也保留了返回类型的引用。

如果你已经知道你的返回类型是一个引用,只要使它显式

auto& calc4() // same as calc2() above
{
    return data;
}