为什么不能将未命名结构用作尾随返回类型

Why can an unnamed struct not be used as a trailing return type?

本文关键字:返回类型 结构 不能 未命名 为什么      更新时间:2023-10-16
struct { int a, b; } f(int x, int y) // OK
{
    return { x, y };
}
auto g(int x, int y) -> struct { int a, b; } // error C2332
{
    return { x, y };
}
int main()
{
    auto n = f(1, 2).a; // OK
}

我的编译器是VC++ 2013 RC。

为什么g错了,而f没问题?

这是VC++的错误吗?

实际上,在C++中,在参数或返回类型中定义类型是非法的,无论是否命名。 请参阅 C++11[diff.decl]:

更改:在C++中,类型可能不在返回或参数类型中定义。在 C 中,允许这些类型定义

因此,实际问题是第一种情况被接受,而不是第二种情况被拒绝。