Added basic support for automated field name retrieval

This commit is contained in:
Patrick Urbanke
2023-11-21 21:07:35 +01:00
parent 44be84e08a
commit 81c14ec63d
3 changed files with 70 additions and 0 deletions
+14
View File
@@ -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
+34
View File
@@ -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
+22
View File
@@ -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