gpt4 book ai didi

c++ - decltype 和隐藏外部名称的类成员名称之间的交互

转载 作者:可可西里 更新时间:2023-11-01 17:39:08 26 4
gpt4 key购买 nike

这段代码

int clash;

struct Foo {
decltype(clash) clash;
};

在 clang 上静默编译,但在 gcc 上编译失败并给出错误

error: declaration of 'int Foo::clash' [-fpermissive]

error: changes meaning of 'clash' from 'int clash' [-fpermissive]

错误的产生似乎需要 2 个成分:

  1. 阴影必须由类成员完成(如果它是函数的局部作用域则没问题)。

  2. decltype([shadowed name]) 必须在声明 [shadowing name] 之前的阴影范围内使用。

我的问题有两个:

  1. gcc 拒绝此代码是否合理?
  2. 标准中哪里这样说的?

最佳答案

gcc 是正确的程序格式错误,尽管这种特殊的违规不需要诊断,因此 clang 不必提供诊断。

如果我们查看 C++11 标准(最接近的草案是 N3337 )部分 3.3.7 类作用域它说:

A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

下一条规则是:

If reordering member declarations in a class yields an alternate valid program under (1) and (2), the program is ill-formed, no diagnostic is required.

我们希望防止在类中重新排序声明会产生不同程序的情况是有道理的。很好奇是否these two rules are redundant or not .

该部分还提供了以下示例:

enum { i = 1 };

class X {
char v[i]; // error: i refers to ::i
// but when reevaluated is X::i
int f() { return sizeof(c); } // OK: X::c
char c;
enum { i = 2 };
};

如果我们使用 gcc ( see it live ) 尝试这个示例,我们会得到一个与您的代码产生的错误几乎相同的错误:

 error: declaration of 'i' [-fpermissive]
enum { i = 2 };
^

error: changes meaning of 'i' from '<anonymous enum> i' [-fpermissive]
enum { i = 1 };

关于c++ - decltype 和隐藏外部名称的类成员名称之间的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26681873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com