better-enums icon indicating copy to clipboard operation
better-enums copied to clipboard

Same value leads to wrong _to_string method

Open cschlosser opened this issue 5 years ago • 4 comments
trafficstars

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?

cschlosser avatar Apr 20 '20 07:04 cschlosser

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.

aantron avatar Apr 20 '20 08:04 aantron

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

cschlosser avatar Apr 20 '20 08:04 cschlosser

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.

aantron avatar Apr 20 '20 08:04 aantron

Okay. Thanks for you quick feedback.

cschlosser avatar Apr 20 '20 08:04 cschlosser