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

时间:2015-09-25 11:23:00

标签: c++ c++11 auto decltype 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 ;
}

第二个代码的区别是什么? 你能举一些例子说明这会产生什么影响,还是会有所作为呢?

1 个答案:

答案 0 :(得分:6)

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