3

Is there a way to construct the elements of an enum from another source of inputs(it is constexpr), like std::array, which is compile time known, like following:

std::array<std::string_view, 3> strs{"AA","BB","CC"};

constexpr int convert(const std::string_view& str) { .... };

enum class MyEnum { 
    AA = convert(strs[0]),  // <== how to generate this 3 lines automatically
    BB = convert(strs[1]), 
    CC = convert(strs[2])
};

The purpose is to maintain only the strs, like adding a new enum element, instead of maintaining two copies of same data. Is there anyway to do this in C++17?

fluter
  • 13,238
  • 8
  • 62
  • 100
  • 1
    https://stackoverflow.com/questions/6635851/real-world-use-of-x-macros – Retired Ninja May 10 '21 at 06:51
  • ah sorry just updated code what i want to do is using the string as the symbol name and convert as the enum values. – fluter May 10 '21 at 06:54
  • The main problem is that the C++ syntax just doesn't allow anything other than literal integer values as enumeration values. It might be possible to construct macros to do what you want, but then the macros must expand to integer literals and nothing else. – Some programmer dude May 10 '21 at 06:56

0 Answers0