Skip to content

Latest commit

 

History

History
70 lines (49 loc) · 1.5 KB

362.md

File metadata and controls

70 lines (49 loc) · 1.5 KB
Info

Example

struct foo {
  int a{};
  int b{};
  int c{};
};

static_assert(3 == std::size(std::meta::nonstatic_data_members_of(^foo)));

https://godbolt.org/z/hr8WvMGYG

Puzzle

  • Can you implement get and get_name for struct members?
template<auto N, class T>
[[nodiscard]] constexpr auto get(const T& t) -> decltype(auto); // TODO

template<auto N, class T>
[[nodiscard]] constexpr auto get_name(const T& t) -> std::string_view; // TODO

struct foo {
  int a{};
  int b{};
  int c{};
};

constexpr foo f{.a=1, .b=2, .c=3};

static_assert(1 == get<0>(f));
static_assert(2 == get<1>(f));
static_assert(3 == get<2>(f));

using std::literals::operator""sv;
static_assert("a"sv == get_name<0>(f));
static_assert("b"sv == get_name<1>(f));
static_assert("c"sv == get_name<2>(f));

https://godbolt.org/z/YGjnhWhzK

Solutions

template<auto N, class T>
[[nodiscard]] constexpr auto get(const T& t) -> decltype(auto) {
  return t.[:std::meta::nonstatic_data_members_of(^T)[N]:];
}

template<auto N, class T>
[[nodiscard]] constexpr auto get_name(const T& t) -> std::string_view {
  return std::meta::name_of(std::meta::nonstatic_data_members_of(^T)[N]);
}

https://godbolt.org/z/qK7K948jn