typesafe enums now inlined

This commit is contained in:
2021-06-11 19:26:28 +02:00
parent 13874fe4c9
commit 79a7f4ef85

View File

@ -7,6 +7,8 @@
// local includes
#include "cppmacros.h"
#define CPPTYPESAFEENUM_SHOULD_INLINE
// These two macros make it possible to define a typesafe enum with parse and
// toString methods
@ -15,6 +17,37 @@
#define DECLARE_TYPESAFE_ENUM_HELPER3(name) else if (str == CPP_STRINGIFY(name)) return TheEnum::name;
#define DECLARE_TYPESAFE_ENUM_HELPER4(name) cb(TheEnum::name, CPP_STRINGIFY(name));
#ifdef CPPTYPESAFEENUM_SHOULD_INLINE
#define DECLARE_TYPESAFE_ENUM(Name, Derivation, Values) \
enum class Name Derivation \
{ \
Values(DECLARE_TYPESAFE_ENUM_HELPER1) \
}; \
inline std::string toString(Name value) \
{ \
switch (value) \
{ \
using TheEnum = Name; \
Values(DECLARE_TYPESAFE_ENUM_HELPER2) \
} \
return std::string{"Unknown " #Name "("} + std::to_string(int(value)) + ')'; \
} \
inline std::optional<Name> parse##Name(std::string_view str) \
{ \
using TheEnum = Name; \
if (false) {} \
Values(DECLARE_TYPESAFE_ENUM_HELPER3) \
return std::nullopt; \
} \
template<typename T> \
void iterate##Name(T &&cb) \
{ \
using TheEnum = Name; \
Values(DECLARE_TYPESAFE_ENUM_HELPER4) \
}
#define IMPLEMENT_TYPESAFE_ENUM(Name, Derivation, Values)
#else
#define DECLARE_TYPESAFE_ENUM(Name, Derivation, Values) \
enum class Name Derivation \
{ \
@ -30,7 +63,7 @@
}
#define IMPLEMENT_TYPESAFE_ENUM(Name, Derivation, Values) \
std::string toString(Name value) \
ExportPrefix std::string toString(Name value) \
{ \
switch (value) \
{ \
@ -39,10 +72,11 @@
} \
return std::string{"Unknown " #Name "("} + std::to_string(int(value)) + ')'; \
} \
std::optional<Name> parse##Name(std::string_view str) \
ExportPrefix std::optional<Name> parse##Name(std::string_view str) \
{ \
using TheEnum = Name; \
if (false) {} \
Values(DECLARE_TYPESAFE_ENUM_HELPER3) \
return std::nullopt; \
using TheEnum = Name; \
if (false) {} \
Values(DECLARE_TYPESAFE_ENUM_HELPER3) \
return std::nullopt; \
}
#endif