是成员声明`decltype(name)name;`在第一个名称引用封闭作用域的本地结构中允许

Is member declaration `decltype(name) name;` permitted in local struct where the first name refers to the enclosing scope?

本文关键字:name 作用域 结构 引用 decltype 声明 成员 第一个      更新时间:2023-10-16

示例:

int main()
{
    int a = 0;
    struct X
    {
        decltype(a) a;
    };
    return 0;
}

decltype(a)是指main中的本地a,而它声明的成员共享相同的名称。

Clang编译时没有任何问题,MSVC14也是如此。

G++抱怨它,添加-fpermissive使它通过

prog.cc:6:21: error: declaration of 'int main()::X::a' [-fpermissive]
         decltype(a) a;
                     ^
prog.cc:3:9: error: changes meaning of 'a' from 'int a' [-fpermissive]
     int a = 0;

哪种行为符合标准?

我认为这违反了〔basic.scope.class〕/1(N3337(:

以下规则描述了类中声明的名称的作用域。

1( […]

2( 类S中使用的名称N在其上下文中以及在S的完整范围中重新评估时应引用相同的声明。违反此规则不需要进行诊断。

由于decltype(a)是指在声明成员变量之前封闭作用域中的声明,但在"在X的已完成作用域中重新求值"时指的是成员,因此程序格式不正确。不需要任何诊断,但GCC无论如何都提供了一个诊断(尽管它相当神秘(。三个编译器的行为都是有效的。