This is an unofficial snapshot of the ISO/IEC JTC1 SC22 WG21 Core Issues List revision 115e. See http://www.open-std.org/jtc1/sc22/wg21/ for the official list.

2024-11-11


2773. Naming anonymous union members as class members

Section: 11.5.2  [class.union.anon]     Status: open     Submitter: Hubert Tong     Date: 2023-07-16

Consider:

  template<typename T>
  int f(T *tp) { return tp->x; }

  static union { int x = f(this); };

According to 11.5.2 [class.union.anon] paragraph 1:

... The names of the members of an anonymous union are bound in the scope inhabited by the union declaration.

Thus, the example above is ill-formed, because the member names are not bound in the scope of the class of the anonymous union. However, there is implementation divergence: clang and gcc accept the example (contrary to the wording), icc rejects. Notwithstanding, this refers to the anonymous union itself, not to an enclosing class, per 7.5.3 [expr.prim.this]. This rule causes rejection of

  struct A {
    int foo();
    union { int x = foo(); };  // error
  };
  A a;

Alternatively, this could be made to refer to the enclosing class object (already the status quo for some implementations). However, that would cause inconsistent treatment for examples like the following:

  struct A {
    int n;
    union {
      void *p = this; // A*
    };
  };
vs.
  struct B {
    int n;
    union {
      void *p = this; // decltype(u)*
    } u;
  };

Possible resolution:

tbd