From 0029f2027a6c8646fb61a09b1791f49bdae6b931 Mon Sep 17 00:00:00 2001 From: qicosmos Date: Wed, 11 Dec 2024 11:26:46 +0800 Subject: [PATCH] [reflection][feat]Add index of (#851) --- include/ylt/reflection/member_value.hpp | 7 +++++++ src/reflection/tests/test_reflection.cpp | 18 ++++++++++++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/include/ylt/reflection/member_value.hpp b/include/ylt/reflection/member_value.hpp index afa307a1a..3ed76b942 100644 --- a/include/ylt/reflection/member_value.hpp +++ b/include/ylt/reflection/member_value.hpp @@ -176,6 +176,13 @@ inline size_t index_of(T& t, Field& value) { return std::distance(offset_arr.begin(), it); } +template +inline size_t index_of(Member member) { + using T = typename member_traits::owner_type; + static auto& t = internal::get_fake_object(); + return index_of(t, t.*member); +} + template inline constexpr std::string_view name_of(T& t, Field& value) { size_t index = index_of(t, value); diff --git a/src/reflection/tests/test_reflection.cpp b/src/reflection/tests/test_reflection.cpp index ae9cbad11..6cd0774c4 100644 --- a/src/reflection/tests/test_reflection.cpp +++ b/src/reflection/tests/test_reflection.cpp @@ -313,6 +313,16 @@ TEST_CASE("test macros") { constexpr size_t size = members_count_v; 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; @@ -366,11 +376,11 @@ TEST_CASE("test macros") { auto& var1 = get<"str">(t); CHECK(var1 == "hello reflection"); - constexpr size_t idx = index_of(); - CHECK(idx == 2); + constexpr size_t i3 = index_of(); + CHECK(i3 == 2); - constexpr size_t idx2 = index_of(); - CHECK(idx2 == 4); + constexpr size_t i4 = index_of(); + CHECK(i4 == 4); #endif constexpr std::string_view name1 = name_of();