Enumeration Link Enumeration and Enumeration Class Compatibility

Suppose there is a C ++ 11 API that uses enumeration classes:

// api.hpp enum class E {A, B, C}; void f(E); ... // api.cpp void f(E e) { if (e == E::A) ... } 

Now suppose I would like to use this API, but I don't have a C ++ 11 compiler. So, I:

  • Modify api.hpp and change the enum class to a simple enumeration.
  • Write code that includes the modified api.hpp and usually uses an API (e.g. f calls).
  • Compile this code with my non-C ++ 11 compiler and bind it to an API implementation that was compiled using the C ++ 11 compiler (using unmodified api.hpp ).

This seems to work with GCC, but is it safe at all, or am I playing with fire (ODR violations, etc.)?

Suppose two compilers are generally compatible with channels, this is only the enum vs. class enum.

+6
source share
2 answers

As ildjarn says, this behavior is undefined. And the reason this can actually happen with real implementations is because regular C ++ 03 enums do not have a fixed base type. Although your enum class type always has "int" as the base type, the corresponding C ++ 03 enum can have the "short" as the base type, making the code incompatible with the layout.

+5
source

You break one rule of definition (ยง3.2 / 5). Result: undefined behavior.

+1
source

Source: https://habr.com/ru/post/914403/


All Articles