C++ Logo

std-proposals

Advanced search

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

From: Jonny Grant <jg_at_[hidden]>
Date: Sat, 20 Jul 2019 21:16:09 +0100
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:18:07