aantron / better-enums

C++ compile-time enum to string, iteration, in a single header file
http://aantron.github.io/better-enums
BSD 2-Clause "Simplified" License
1.67k stars 173 forks source link

Same value leads to wrong _to_string method #84

Open cschlosser opened 4 years ago

cschlosser commented 4 years ago

Hi,

there seems to be a problem when assigning the same integer value to two different enum values. The _to_string() method will then print the name of the first enum value this integer was assigned to.

Example:

BETTER_ENUM(FooBar, int, Foo = 1, Bar = 1)

std::cout << "Foo=" << (+FooBar::Foo)._to_string() << std::endl
          << "Bar=" << (+FooBar::Bar)._to_string() << std::endl;
//Foo=Foo
//Bar=Foo

Godbolt

This may seem weird but is explicitly allowed by the C99 standard WG14/N1256 6.7.2.2/3.

Sorry if I missed this as known behavior somewhere, I only found a short reference to it in the FAQ related to the use of indices for representation.

From your FAQ

Worse, Better Enums become sensitive to declaration order even when initializers are given explicitly.

This is unfortunately true for the current implementation as well, even though in a different way than you're talking about in the FAQ.

I can see why it's implemented this way but is there a possibility of maybe having a "slower" or less "smart" enum with a pretty much equal interface that can solve this?

aantron commented 4 years ago

is there a possibility of maybe having a "slower" or less "smart" enum with a pretty much equal interface that can solve this?

If the enum at runtime is still represented as an integer value (rather than an index into the enum declaration or otherwise), I don't think there is a way for _to_string to distinguish the names that map to that value.

cschlosser commented 4 years ago

What about an "Indexed" enum version with a limited/different feature set?

aantron commented 4 years ago

It's possible to create it as a variant, but it would be a different library. The direct representation is one of the "features" of this library (and typical enums in C++ and similar languages). It allows direct usage in reading/writing data formats, for example.

cschlosser commented 4 years ago

Okay. Thanks for you quick feedback.