mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-12-06 10:46:18 +08:00
add rfl::enum_to_string and rfl::string_to_enum
This commit is contained in:
@@ -33,6 +33,7 @@
|
||||
#include "rfl/define_named_tuple.hpp"
|
||||
#include "rfl/define_tagged_union.hpp"
|
||||
#include "rfl/define_variant.hpp"
|
||||
#include "rfl/enums.hpp"
|
||||
#include "rfl/extract_discriminators.hpp"
|
||||
#include "rfl/field_type.hpp"
|
||||
#include "rfl/fields.hpp"
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
#ifndef RFL_ENUMS_HPP_
|
||||
#define RFL_ENUMS_HPP_
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "Result.hpp"
|
||||
#include "internal/enums/StringConverter.hpp"
|
||||
#include "internal/enums/is_scoped_enum.hpp"
|
||||
|
||||
namespace rfl {
|
||||
|
||||
template <internal::enums::is_scoped_enum EnumType>
|
||||
std::string enum_to_string(EnumType _enum) {
|
||||
return rfl::internal::enums::StringConverter<EnumType>::enum_to_string(_enum);
|
||||
}
|
||||
|
||||
template <internal::enums::is_scoped_enum EnumType>
|
||||
rfl::Result<EnumType> string_to_enum(const std::string& _str) {
|
||||
return rfl::internal::enums::StringConverter<EnumType>::string_to_enum(_str);
|
||||
}
|
||||
|
||||
} // namespace rfl
|
||||
|
||||
#endif // RFL_ENUMS_HPP_
|
||||
@@ -25,6 +25,23 @@ void test() {
|
||||
const auto circle = Circle{.radius = 2.0, .color = Color::green};
|
||||
|
||||
write_and_read(circle, R"({"radius":2.0,"color":"green"})");
|
||||
|
||||
auto mutable_circle = Circle{.radius = 2.0, .color = Color::green};
|
||||
if (auto color = rfl::string_to_enum<Color>("red"); color) {
|
||||
mutable_circle.color = *color;
|
||||
}
|
||||
write_and_read(mutable_circle, R"({"radius":2.0,"color":"red"})");
|
||||
|
||||
if (auto color = rfl::string_to_enum<Color>("bart"); color) {
|
||||
mutable_circle.color = *color;
|
||||
}
|
||||
write_and_read(mutable_circle, R"({"radius":2.0,"color":"red"})");
|
||||
|
||||
if (auto color = rfl::string_to_enum<Color>(rfl::enum_to_string(Color::blue));
|
||||
color) {
|
||||
mutable_circle.color = *color;
|
||||
}
|
||||
write_and_read(mutable_circle, R"({"radius":2.0,"color":"blue"})");
|
||||
}
|
||||
|
||||
} // namespace test_enum
|
||||
|
||||
Reference in New Issue
Block a user