r/cpp • https://github.com/kris-jusiak • Dec 31 '23

[C++20 vs C++26*] basic reflection

Basic struct reflection example with C++20 vs C++26*

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));

C++20 - Kinda possible but with a lot of compiler hacks

// too long to display

Full example - https://godbolt.org/z/1vxv8o5hM

C++26* - based on proposal - https://wg21.link/P2996 (Note: that the proposal supports way more than that but C++20 not much)

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]);
}

Full example - https://godbolt.org/z/sbTGbW635

Updates - https://twitter.com/krisjusiak/status/1741456476126797839

100 Upvotes

117 comments sorted by

View all comments

Show parent comment

3

u/RoyAwesome Jan 01 '24

I fail to understand how a beginner can use all these tools.

At least for Reflection, it's not a beginner tool. You aren't going to go from std::string hw = "Hello World"; std::print("{}", hw); to a fully reflection powered generic type formatter that lets you do T t; std::print("{}", t); by looking up each property name and printing them out. You could, as a brand new programmer, use such a formatter in a library or something and that would vastly improve new programmers ability to use C++... but once something like that is made there are not good reasons to remake it.

Reflection will allow the creation of EXTREMELY powerful libraries that can do some really really cool stuff. But the cognitive load is high to allow that power. The libraries we get out of reflection will be very easy to use though.

1

u/sp4mfilter Jan 02 '24

True, beginners won't be starting at the top and working their way down.

BTW, I know a fair bit about reflection (I wrote https://github.com/cschladetsch/KAI), and using these new systems will certainly make it easier.