0
enum class A
{
    type_a,
    type_b
};
#define name(a) #a

int main()
{
    cout << name(A::type_a) << endl;
}

I can output the 'enum class' variable'name(output 'A::type_a', because it is easier to understand than its value) as above.But if I put the output in a function and use 'A::type_a' as its input variable like below, the 'enum class' variable'name will only output the input variable's name(output 'a' but not 'A::type_a').

void func(A a)
{
    cout << name(a) << endl;
}

int main()
{
    func(A::type_a);
}

Though I can use 'switch case' to list every name of the enum, but is there any better method that I would not modify the output function even though when I add or delete any item in the enum.

f1msch
  • 509
  • 2
  • 12
  • 2
    your macro just returns whatever it gets as input as a string. If you write `name(asdf)`, it will just return `asdf`. – Raildex Oct 27 '21 at 05:07
  • C++ doesn't have [type introspection](https://en.wikipedia.org/wiki/Introspection_(computer_science)). It's impossible to do what you want without actually mapping the enumerations to an string in your code. – Some programmer dude Oct 27 '21 at 05:13
  • you can use some kind of hack code as below switch(a) { case type_a: cout << name(type_a) << endl; } – soumya sambit Kunda Oct 27 '21 at 05:21
  • @soumyasambitKunda But when I add or delete any item in the enum, I must change the 'switch' code at the same time. It is so unconvinient and eaier to make wrong – f1msch Oct 27 '21 at 05:42
  • @f1msch the question is why would you want to do it in the first place. – Raildex Oct 27 '21 at 05:46
  • See this answer: https://stackoverflow.com/a/17465919/2527795 – VLL Oct 27 '21 at 05:51
  • Does this answer your question? [Creating a string list and an enum list from a C++ macro](https://stackoverflow.com/questions/5530248/creating-a-string-list-and-an-enum-list-from-a-c-macro) – VLL Oct 27 '21 at 05:52

1 Answers1

0

This requires language support for reflection, so it is currently not possible in the standard.

However, you can use third-party library such as Magic Enum to get the variable name of the enum:

#include <iostream>
#include <magic_enum.hpp>

enum class A
{
  type_a,
  type_b
};

template<class E>
void func(E e)
{
  std::cout << "enum name: " << magic_enum::enum_name(e) << "\n";
}

int main()
{
  func(A::type_a);
}

Demo.

康桓瑋
  • 33,481
  • 5
  • 40
  • 90