【发布时间】:2019-09-09 04:51:48
【问题描述】:
我发现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这两个函数有什么区别。所以只要输出相同,为什么我需要使用尾随返回类型?
【问题讨论】:
-
get_diag2不应编译,除非您使用 C++14 或更高版本。你确定你是用 C++11 编译的吗? -
@NathanOliver:是的,你是真的。当我在 C++11 编译器上尝试它时,它无法抱怨:`'auto' return without trailing return type;推导的返回类型是 C++14 扩展。请添加它作为答案,以便它可能对其他 OPs 有用。
标签: c++ c++11 auto trailing-return-type