4

Why does the code below compile without any errors?

enum class Enumeration;
void func()
{
    auto enumeration = static_cast<Enumeration>(2);
    auto value = static_cast<int>(enumeration);
}
Donqustix
  • 75
  • 6
  • 2
    Possible duplicate of [Why is initialization of enum class temporaries with arbitrary values allowed?](https://stackoverflow.com/questions/30852922/why-is-initialization-of-enum-class-temporaries-with-arbitrary-values-allowed) – anatolyg Jul 10 '17 at 14:56
  • 1
    Is there some reason it shouldn't? – Lightness Races in Orbit Jul 10 '17 at 14:57
  • 6
    You have declated a: _"Opaque enum declaration: defines the enumeration type but not its enumerators: after this declaration, the type is a complete type and its size is known."_ source: http://en.cppreference.com/w/cpp/language/enum – Richard Critten Jul 10 '17 at 14:58
  • 1
    the standard allows this. it may not be exceedingly useful. see also here what it was originally intended for: https://stackoverflow.com/a/18338930/1132334 – Cee McSharpface Jul 10 '17 at 15:01
  • 1
    So, it's _not_ incomplete; it just does not have any enumerators. – underscore_d Jul 10 '17 at 15:06
  • Examples when such enums are useful would be an excellent answer. – Vorac Jul 10 '17 at 15:08
  • @RichardCritten You should turn that into an answer. You have a lot of comments that are good answers. – Ron Jul 10 '17 at 15:09
  • 2
    It's because of [`[dcl.enum]/3`](http://eel.is/c++draft/dcl.enum#3), but I don't know what the motivation is. – Rakete1111 Jul 10 '17 at 15:14

1 Answers1

5

It compiles because the compiler knows at compile time the size of Enumeration (which happens to be empty).

You see it explicitly using the following syntax:

 enum class Enumeration : short;

The compiler knows everything there is to know about the Enumeration. Enumeration is a opaque-enum-declaration which means also that the type is complete i.e. you can use sizeofon it. If needed you can specify the list of enumerators in a later redeclaration (unless the redeclaration comes with a different underlying type, obviously).

Note that since you are using enum class usage of static_cast is mandatory.

  • Strongly typed enum does not allow implicit conversion to int but you can safely use static_cast on them to retrieve their integral value.

They are still enum afterall.

Quoting cppreference

There are no implicit conversions from the values of a scoped enumerator to integral types, although static_cast may be used to obtain the numeric value of the enumerator.

More on this topic here: How to automatically convert strongly typed enum into int?

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36