refactor: use magic_enum instead of switch.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "util/string.h"
|
||||
#include <magic_enum.hpp>
|
||||
|
||||
namespace di {
|
||||
|
||||
@@ -26,33 +26,11 @@ public:
|
||||
|
||||
constexpr DeclType(Enum value) : m_data(value) {}
|
||||
constexpr explicit DeclType(std::string_view str) {
|
||||
using namespace util::string;
|
||||
|
||||
// clang-format off
|
||||
|
||||
switch (H(str)) {
|
||||
#define HSTR(x) \
|
||||
case H(#x): \
|
||||
m_data = x; \
|
||||
break
|
||||
HSTR(Function);
|
||||
HSTR(CXXDeductionGuide);
|
||||
HSTR(CXXMethod);
|
||||
HSTR(CXXConstructor);
|
||||
HSTR(CXXConversion);
|
||||
HSTR(CXXDestructor);
|
||||
HSTR(Var);
|
||||
HSTR(Decomposition);
|
||||
HSTR(ImplicitParam);
|
||||
HSTR(OMPCapturedExpr);
|
||||
HSTR(ParamVar);
|
||||
HSTR(VarTemplateSpecialization);
|
||||
#undef HSTR
|
||||
default:
|
||||
throw ConvertEnumException(str, TypeOnly<Enum>{});
|
||||
if (auto value = magic_enum::enum_cast<Enum>(str)) {
|
||||
m_data = *value;
|
||||
} else {
|
||||
throw EnumCastException(str, TypeOnly<Enum>{});
|
||||
}
|
||||
|
||||
// clang-format on
|
||||
}
|
||||
|
||||
constexpr bool is_function() const {
|
||||
@@ -87,7 +65,7 @@ public:
|
||||
HSTR(VarTemplateSpecialization);
|
||||
#undef HSTR
|
||||
default:
|
||||
throw ConvertEnumException(m_data);
|
||||
throw EnumCastException(m_data);
|
||||
}
|
||||
|
||||
// clang-format on
|
||||
|
||||
@@ -107,13 +107,12 @@ public:
|
||||
constexpr std::string category() const { return "exception.unix"; }
|
||||
};
|
||||
|
||||
class ConvertEnumException : public RuntimeException<ConvertEnumException> {
|
||||
class EnumCastException : public RuntimeException<EnumCastException> {
|
||||
public:
|
||||
// TODO: compile-time reflection.
|
||||
// TODO: remove helper.
|
||||
|
||||
template <Enumerate T>
|
||||
explicit ConvertEnumException(T enum_val)
|
||||
explicit EnumCastException(T enum_val)
|
||||
: RuntimeException("Unable to convert string to enumeration value because "
|
||||
"input value is bad.") {
|
||||
add_context("enum_type", typeid(T).name());
|
||||
@@ -121,14 +120,14 @@ public:
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
explicit ConvertEnumException(std::string_view enum_str, TypeOnly<T>)
|
||||
explicit EnumCastException(std::string_view enum_str, TypeOnly<T>)
|
||||
: RuntimeException("Unable to convert enumeration value to string because "
|
||||
"input value is bad.") {
|
||||
add_context("enum_type", typeid(T).name());
|
||||
add_context("string", enum_str);
|
||||
}
|
||||
|
||||
constexpr std::string category() const { return "exception.enumconvert"; }
|
||||
constexpr std::string category() const { return "exception.magicenum"; }
|
||||
};
|
||||
|
||||
} // namespace di
|
||||
|
||||
Reference in New Issue
Block a user