我可以使用 auto 或 decltype 代替尾随 return 类型吗?
Can i use auto or decltype instead trailing return type?
我发现 trailing return type
很容易定义函数的 return,return 是一个复杂的类型,例如:
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
有什么区别。所以只要输出相同为什么我需要使用尾随 return 类型?
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 编译器中运行。使用没有尾随 return 类型的 auto
已被添加到 C++14 中,其行为类似于 auto 在将其用于变量时的工作方式。这意味着它永远不会 return 引用类型,所以你必须使用 auto&
到 return 对你想要的东西的引用 return.
如果您不知道应该 return 一个引用还是一个值(这种情况在泛型编程中经常发生),那么您可以使用 decltyp(auto)
作为 return 类型。例如
template<class F, class... Args>
decltype(auto) Example(F func, Args&&... args)
{
return func(std::forward<Args>(args)...);
}
如果 func
return 是值, 将 return 是值,如果 func
return 是引用,return 是引用。
简而言之,如果您使用的是 C++11,则必须指定 return 类型,可以在前面或作为尾随 return 类型。在 C++14 及更高版本中,您可以只使用 auto
/decltype(auto)
并让编译器为您处理它。
我发现 trailing return type
很容易定义函数的 return,return 是一个复杂的类型,例如:
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
有什么区别。所以只要输出相同为什么我需要使用尾随 return 类型?
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 编译器中运行。使用没有尾随 return 类型的 auto
已被添加到 C++14 中,其行为类似于 auto 在将其用于变量时的工作方式。这意味着它永远不会 return 引用类型,所以你必须使用 auto&
到 return 对你想要的东西的引用 return.
如果您不知道应该 return 一个引用还是一个值(这种情况在泛型编程中经常发生),那么您可以使用 decltyp(auto)
作为 return 类型。例如
template<class F, class... Args>
decltype(auto) Example(F func, Args&&... args)
{
return func(std::forward<Args>(args)...);
}
如果 func
return 是值, 将 return 是值,如果 func
return 是引用,return 是引用。
简而言之,如果您使用的是 C++11,则必须指定 return 类型,可以在前面或作为尾随 return 类型。在 C++14 及更高版本中,您可以只使用 auto
/decltype(auto)
并让编译器为您处理它。