2#ifndef LIBSBX_REFLECTION_DESCROPTION_HPP_
3#define LIBSBX_REFLECTION_DESCROPTION_HPP_
10#include <libsbx/reflection/member.hpp>
11#include <libsbx/reflection/enumerator.hpp>
13namespace sbx::reflection {
15template<
typename Type>
18template<
typename Type>
19concept reflectable_struct = std::is_class_v<Type> &&
requires() {
24template<
typename Type>
25concept reflectable_enum = std::is_enum_v<Type> &&
requires() {
26 { description<Type>::name() } -> std::convertible_to<std::string_view>;
27 { description<Type>::enumerators() };
30template<
typename Type>
31concept reflectable = reflectable_struct<Type> || reflectable_enum<Type>;
33template<reflectable_struct Type,
typename Callback>
34auto for_each(Type& instance, Callback&& callback) ->
void {
35 constexpr auto members = description<Type>::members();
37 std::apply([&](
auto const&... field) {
38 (callback(field.name, instance.*(field.pointer)), ...);
42template<reflectable_struct Type,
typename Callback>
43auto for_each(Type
const& instance, Callback&& callback) ->
void {
44 constexpr auto members = description<Type>::members();
46 std::apply([&](
auto const&... field) {
47 (callback(field.name, instance.*(field.pointer)), ...);
51template<reflectable_struct Type,
typename Callback>
52auto visit_member(Type& instance, std::string_view name, Callback&& callback) ->
bool {
55 for_each(instance, [&](
auto member_name,
auto& value) {
56 if (!found && member_name == name) {
65template<reflectable_enum Enum,
typename Callback>
66auto for_each(Callback&& callback) ->
void {
67 constexpr auto enumerators = description<Enum>::enumerators();
69 std::apply([&](
auto const&... entry) {
70 (callback(entry.name, entry.value), ...);
74template<reflectable_enum Enum>
75auto to_string(Enum value) -> std::string_view {
76 auto result = std::string_view{
"<unknown>"};
78 for_each<Enum>([&](
auto name,
auto entry) {
87template<reflectable_enum Enum>
88auto from_string(std::string_view name) -> std::optional<Enum> {
89 auto result = std::optional<Enum>{};
91 for_each<Enum>([&](
auto entry_name,
auto entry) {
92 if (entry_name == name) {
100template<reflectable_enum Enum>
101auto from_string_or(std::string_view name,
const Enum default_value) -> Enum {
102 auto result = from_string<Enum>(name);
104 return result ? *result : default_value;
Definition: description.hpp:16