C++ Logo

std-proposals

Advanced search

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

From: Andrew Tomazos <andrewtomazos_at_[hidden]>
Date: Sun, 21 Jul 2019 09:07:41 +1000
Sebastian is correct. This use case has been subsumed by the upcoming
reflection feature of C++26 (estimated) that will allow you to (among other
things) get the names of entities (including, but not limited to,
enumerations and enumerators) in a way that you can write, once, a general
library function like:

    template<typename E>
    constexpr string_like enum_to_string(E e) { /* usage of reflection
feature */ }

and then for any enumerator:

    enum Color { Red, Blue };

    Color c = Red;
    cout << enum_to_string(c); // prints "Red"

-Andrew

On Sun, Jul 21, 2019 at 6:16 AM Jonny Grant via Std-Proposals <
std-proposals_at_[hidden]> 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
> .
>
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> http://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2019-07-20 18:09:51