为什么在尾随返回类型中使用decltype
Why decltype is used in trailing return types?
考虑以下代码:
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;
}
相关文章:
- c++ 11 带有 decltype 的尾随返回类型无法按预期工作
- decltype(auto) 是否使尾随返回类型过时?
- 元函数使用 decltype 返回元素类型
- 如何使用非尾随 decltype 返回类型定义行外类模板成员函数
- clang 拒绝具有尾随 decltype 返回类型的模板调用是否正确,具体取决于其重载之一?
- 尾随返回类型中去 decltype 的原因
- decltype(function_name) 的返回类型是完全无用的
- 我可以使用自动或 decltype 代替尾随返回类型吗?
- C++11 decltype 返回正确的类型,但代码无法编译
- 模板函数的返回类型未知,使用 decltype 时代码重复
- GCC 中的编译器错误,但在将 decltype 与具有尾随返回类型语法的模板化成员函数一起使用时没有 clang
- C++11 中的 decltype(auto) - 推断返回类型
- 使用decltype尾部返回类型专门化函数模板
- 字符串的decltype和const引用返回类型
- decltype用于递归变元函数模板的返回类型
- 如何使用decltype作为模板化类的返回类型的模板参数
- 自动返回类型哪个更好:decltype 或 std::common_type<>::type(如果可能)?
- 如何在 C++11 之前模拟尾随返回类型的 decltype
- 为什么返回类型中的decltype表达式必须在符号名称中损坏
- 为什么decltype返回类型在递归模板中失败,而返回类型演绎却工作得很好?