我可以使用自动或 decltype 代替尾随返回类型吗?
Can i use auto or decltype instead trailing return type?
我发现定义返回复杂类型的函数trailing return type
很容易,例如:
auto get_diag(int(&ar)[3][3])->int(&)[3]{ // using trailing return type
static int diag[3]{
ar[0][0], ar[1][1], ar[2][2]
};
return diag;
}
auto& get_diag2(int(&ar)[3][3]){ // adding & auto because otherwise it converts the array to pointer
static int diag[3]{
ar[0][0], ar[1][1], ar[2][2]
};
return diag;
}
int main(){
int a[][3]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
decltype(get_diag(a)) diag{
get_diag(a)
};
for (auto i : diag)
std::cout << i << ", ";
std::cout << std::endl;
decltype(get_diag2(a)) diag2{
get_diag2(a)
};
for (auto i : diag2)
std::cout << i << ", ";
std::cout << std::endl;
std::cout << std::endl;
}
- 我想知道
get_diag
和get_diag2
的功能有什么区别。所以只要输出相同,为什么我需要使用尾随返回类型?
auto& get_diag2(int(&ar)[3][3]){ // adding & auto because otherwise it converts the array to pointer
static int diag[3]{
ar[0][0], ar[1][1], ar[2][2]
};
return diag;
}
在 C++11 编译器中不起作用。 使用不带尾随返回类型的auto
被添加到 C++14 中,其作用类似于将其用于变量时的 auto 工作方式。 这意味着它永远不会返回引用类型,因此您必须使用 auto&
返回对要返回的内容的引用。
如果您不知道是否应该返回引用或值(这在泛型编程中经常发生(,则可以使用 decltyp(auto)
作为返回类型。 例如
template<class F, class... Args>
decltype(auto) Example(F func, Args&&... args)
{
return func(std::forward<Args>(args)...);
}
如果func
按值返回,则按值返回,如果返回引用,则按引用返回func
。
简而言之,如果您使用的是 C++11,则必须指定返回类型,无论是在前面还是作为尾随返回类型。 在 C++14 及更高版本中,您只需使用 auto
/decltype(auto)
,让编译器为您处理。
相关文章:
- c++ 11 带有 decltype 的尾随返回类型无法按预期工作
- decltype(auto) 是否使尾随返回类型过时?
- 如何使用非尾随 decltype 返回类型定义行外类模板成员函数
- clang 拒绝具有尾随 decltype 返回类型的模板调用是否正确,具体取决于其重载之一?
- 尾随返回类型中去 decltype 的原因
- decltype(function_name) 的返回类型是完全无用的
- 我可以使用自动或 decltype 代替尾随返回类型吗?
- 模板函数的返回类型未知,使用 decltype 时代码重复
- GCC 中的编译器错误,但在将 decltype 与具有尾随返回类型语法的模板化成员函数一起使用时没有 clang
- C++11 中的 decltype(auto) - 推断返回类型
- 使用decltype尾部返回类型专门化函数模板
- 字符串的decltype和const引用返回类型
- decltype用于递归变元函数模板的返回类型
- 如何使用decltype作为模板化类的返回类型的模板参数
- 自动返回类型哪个更好:decltype 或 std::common_type<>::type(如果可能)?
- 如何在 C++11 之前模拟尾随返回类型的 decltype
- 为什么返回类型中的decltype表达式必须在符号名称中损坏
- 使用"-> decltype"推断返回类型
- 使用decltype声明返回类型
- 使用c++ 14使用多个返回类型decltype(auto)