Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum bitfield and aggregate initialization

The following code is accepted by clang 6.0.0 but rejected by gcc 8.2

enum class E {
  Good, Bad,
};

struct S {
  E e : 2;
  int dummy;
};

S f() {
  return {E::Good, 100};
}

Live godbolt example

The GCC complains

error: could not convert '{Good, 100}' from '<brace-enclosed initializer list>' to 'S'

Which one is correct? Where in the standard talks about this situation?

like image 506
Kan Li Avatar asked Sep 05 '18 23:09

Kan Li


1 Answers

return {E::Good, 100}; performs copy list initialization of the return value. The effect of this list initialization is an aggregate initialization.

So is S an aggregate? The description of an aggregate varies depending on which version of C++ you're using, but in all cases S should be an aggregate so this should compile. Clang (and MSVC) have the correct behavior.

The fix is simple, though. Change your return statement to return the correctly typed object:

return S{E::Good, 100};
like image 83
1201ProgramAlarm Avatar answered Sep 28 '22 09:09

1201ProgramAlarm