Skip to content

Commit

Permalink
[reflection][feat]Add index of (#851)
Browse files Browse the repository at this point in the history
  • Loading branch information
qicosmos authored Dec 11, 2024
1 parent 4490d48 commit 0029f20
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
7 changes: 7 additions & 0 deletions include/ylt/reflection/member_value.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,13 @@ inline size_t index_of(T& t, Field& value) {
return std::distance(offset_arr.begin(), it);
}

template <typename Member>
inline size_t index_of(Member member) {
using T = typename member_traits<Member>::owner_type;
static auto& t = internal::get_fake_object<T>();
return index_of(t, t.*member);
}

template <typename T, typename Field>
inline constexpr std::string_view name_of(T& t, Field& value) {
size_t index = index_of(t, value);
Expand Down
18 changes: 14 additions & 4 deletions src/reflection/tests/test_reflection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,16 @@ TEST_CASE("test macros") {
constexpr size_t size = members_count_v<dummy_t>;
static_assert(size == 3);

constexpr auto idx = index_of<&simple2::age>();
static_assert(idx == 3);
constexpr auto idx2 = index_of<&simple2::id>();
static_assert(idx2 == 1);

auto i = index_of(&simple::id);
CHECK(i == 1);
i = index_of(&simple::age);
CHECK(i == 3);

auto ref_tp = object_to_tuple(t);
auto& c = std::get<0>(ref_tp);
c = 10;
Expand Down Expand Up @@ -366,11 +376,11 @@ TEST_CASE("test macros") {
auto& var1 = get<"str">(t);
CHECK(var1 == "hello reflection");

constexpr size_t idx = index_of<simple2, "str">();
CHECK(idx == 2);
constexpr size_t i3 = index_of<simple2, "str">();
CHECK(i3 == 2);

constexpr size_t idx2 = index_of<simple2, "no_such">();
CHECK(idx2 == 4);
constexpr size_t i4 = index_of<simple2, "no_such">();
CHECK(i4 == 4);
#endif

constexpr std::string_view name1 = name_of<simple2, 2>();
Expand Down

0 comments on commit 0029f20

Please sign in to comment.