C++ Logo

std-proposals

Advanced search

Re: enum class value name string via something similar to typeid().name() ?

From: Jonny Grant <jg_at_[hidden]>
Date: Sat, 20 Jul 2019 21:34:08 +0100
Hi Sebastian

Many thanks for your reply. yes, better I avoid using this typeid(), it
only gives the type.. not the enum class name "Red" I had hoped for etc

Yes, I would prefer to avoid using typeid().

My proposal would be if there could be just a .name() on all 'enum class' ?

Thanks
Jonny


On 20/07/2019 21:27, Sebastian Büttner wrote:
> Hi Jonny,
>
> you might want to wait for reflection to do such things.
>
> Relying on the name returned by a std::type_info object is not a save
> way anyway since the returned name is implementation defined.
>
> See: http://eel.is/c++draft/type.info#9 - This is also why you get
> something "strange" like 5Color for your color enum on some
> implementations.
>
> Cheers,
> Sebastian
>
> On 2019-07-20 22:16, Jonny Grant via Std-Proposals wrote:
>> Hello
>>
>> Could I ask if enum class has been considered to add a way to get a
>> string representation from an enum? ie "Red" and "Blue" below.
>> typeid() just returns the enum class name.
>>
>> Very useful for logs/debugging.
>>
>> Read the initial link about enum class:
>> http://www.stroustrup.com/C++11FAQ.html#enum
>>
>>
>> ie, what I am asking is if for example:
>> // g++-8 -Wall -o typeid typeid.cpp
>>
>> #include <iostream>
>> #include <string>
>> #include <typeinfo>
>>
>> enum class Color { Red, Blue };
>>
>> int main()
>> {
>> Color c = Color::Red;
>>
>> std::cout << "my enum is " << typeid(c).name() << std::endl;
>>
>> std::cout << "my enum is " << c.name() << std::endl;
>>
>> std::cout << "my enum is " << Color::Blue.name() << std::endl;
>> }
>>
>>
>> (if it compiled) the output would be:
>>
>> my enum is Color
>> my enum is Red
>> my enum is Blue
>>
>> But the later two lines do not compile
>>
>> The first does work, but only gives the type.
>>
>>
>> $ ./typeid
>> my enum is 5Color
>>
>>
>> Strange that this one is '5Color'
>>
>>
>>
>> Could it be done by the typeid() on enum class?
>>
>>
>> This saves me needing to write for every enum
>>
>> const char * get_enum_str(Color value);
>>
>>
>> There are a lot of posts online discussing similar
>>
>> https://stackoverflow.com/questions/28828957/enum-to-string-in-modern-c11-c14-c17-and-future-c20
>>
>>
>>
>> Has there been a proposal someone could point me to please?
>>
>> Jonny
>> .
>


Received on 2019-07-20 15:36:07