Title
Naming anonymous union members as class members
Status
open
Section
11.5.2 [class.union.anon]
Submitter
Hubert Tong

Created on 2023-07-16.00:00:00 last changed 17 months ago

Messages

Date: 2023-08-14.07:00:34

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

History
Date User Action Args
2023-07-16 00:00:00admincreate