mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-12-06 18:56:19 +08:00
Added basic support for automated field name retrieval
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
#ifndef RFL_INTERNAL_FAKEOBJECT_HPP_
|
||||
#define RFL_INTERNAL_FAKEOBJECT_HPP_
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
|
||||
/// This is required to automatically retrieve the names.
|
||||
template <class T>
|
||||
extern T fake_object;
|
||||
|
||||
} // namespace internal
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,34 @@
|
||||
#ifndef RFL_INTERNAL_GETFIELDNAME_HPP_
|
||||
#define RFL_INTERNAL_GETFIELDNAME_HPP_
|
||||
|
||||
#include <memory>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#include "rfl/internal/fake_object.hpp"
|
||||
#include "rfl/internal/is_field.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
|
||||
template <auto* ptr>
|
||||
std::string get_field_name() {
|
||||
using Type = std::decay_t<std::remove_pointer_t<decltype(ptr)>>;
|
||||
if constexpr (rfl::internal::is_field_v<Type>) {
|
||||
using Name = typename Type::Name;
|
||||
return Name().str();
|
||||
} else {
|
||||
const std::string func_name =
|
||||
std::source_location::current().function_name();
|
||||
const size_t pos_fake_object = func_name.find("fake_object");
|
||||
const size_t begin = func_name.find_first_of("::", pos_fake_object) + 2;
|
||||
const size_t end = func_name.find_first_of(")", begin);
|
||||
return func_name.substr(begin, end - begin);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,22 @@
|
||||
#ifndef RFL_INTERNAL_GETFIELDNAMES_HPP_
|
||||
#define RFL_INTERNAL_GETFIELDNAMES_HPP_
|
||||
|
||||
#include <array>
|
||||
|
||||
#include "rfl/internal/fake_object.hpp"
|
||||
#include "rfl/internal/get_field_name.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
|
||||
template <class MyStruct>
|
||||
auto get_field_names() {
|
||||
auto& [f1, f2] = fake_object<MyStruct>;
|
||||
return std::array<std::string, 2>(
|
||||
{get_field_name<&f1>(), get_field_name<&f2>()});
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user