I would like to create a macro to define an enum and also create a helper function that converts an int to that enum and returns std::nullopt if there is no enum with the passed value.
I would like to be able to create an enum like such:
SOME_MACRO(ENUM_NAME,
(foo, 1),
(bar, 5),
)
(Note that the values of the enum are not sequential).
I have to create a lot of enums like this so I would like to only have one definition of each enum where I need to change if the values change.
Here is the closest I have gotten:
#define DEFINE_ENUM_WITH_CONVERSION(EnumName, ENUM_LIST)
enum class EnumName {
ENUM_LIST(ENUM_ENTRY)
};
std::optional<EnumName> intTo##EnumName(int value) {
switch (value) {
ENUM_LIST(ENUM_CASE)
default:
return std::nullopt;
}
}
// Helper macros for enum definition and switch cases
#define ENUM_ENTRY(name, value) name = value,
#define ENUM_CASE(name, value) case value: return EnumName::name;
// Define the list of enum values
#define VALUE_LIST(X)
X(value1, 0)
X(value2, 1)
// Correct usage of the macro to define the enum and the conversion function
DEFINE_ENUM_WITH_CONVERSION(Value, VALUE_LIST)
But in #define ENUM_CASE(name, value) case value: return EnumName::name;
EnumName
is not getting replaced to the actual name.
NOTE: I tried using the using enum EnumName
keyword but I can only use c++17, not c++20.
EDIT: The macro I posted is the closest I got, there is no need to build upon it if there is a better way to do it.
Thanks in advance,
Roconx.
Roconx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2