Interaction between decltype and class member name shadowing an external name

前端 未结 1 846
野趣味
野趣味 2020-11-30 13:09

This code

int clash;

struct Foo {
  decltype(clash) clash;
};

compiles silently on clang, but fails to compile on gcc giving the errors

相关标签:
1条回答
  • 2020-11-30 13:18

    gcc is correct the program is ill-formed, although this particular violation does not require a diagnostic so clang does not have to provide one.

    If we look at the C++11 standard(The closest draft would be N3337) section 3.3.7 Class scope it says:

    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.

    and the next rule says:

    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.

    It makes sense we would want to prevent situations where reordering the declarations in a class give a different program. It is curious whether these two rules are redundant or not.

    The section also provides the following example:

    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 };
    };
    

    and if we try this example with gcc (see it live), we get an almost identical error to one your code produces:

     error: declaration of 'i' [-fpermissive]
     enum { i = 2 };
              ^
    
     error: changes meaning of 'i' from '<anonymous enum> i' [-fpermissive]
     enum { i = 1 };
    
    0 讨论(0)
提交回复
热议问题