Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Same value leads to wrong _to_string method #84

Open
cschlosser opened this issue Apr 20, 2020 · 4 comments
Open

Same value leads to wrong _to_string method #84

cschlosser opened this issue Apr 20, 2020 · 4 comments

Comments

@cschlosser
Copy link

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
Copy link
Owner

aantron commented Apr 20, 2020

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
Copy link
Author

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

@aantron
Copy link
Owner

aantron commented Apr 20, 2020

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
Copy link
Author

Okay. Thanks for you quick feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants