There is a C++ Technical Specification on static reflection (current PDF draft and cppreference page) which might move into C++23 or later.
Would it be possible in the current draft (I understand syntax is perhaps not fixed yet) to access struct fields / call class member functions by name?
For instance
struct Test {
int x;
int y;
};
Test foo;
auto meta = reflexpr(foo); // access meta information about class
some_magic_setter<"x", meta>(foo, 5); // ??? Should do: `foo.x = 5`
Would this be possible and if yes how ?
EDIT: When I look into the TS draft I find most of the functions are named 'get_XX' (like get_type
, get_scope
, ...) or 'is_XXX' (like is_private
, ...) which seems to to only give information (which is obvoiously the purpose of reflection). However, I cannot find anything that seems to allow member access of a given object. Any hints are welcome.
get_pointer<X>
gets you a pointer to member, get_name<X>
gets its name. Throw in some iterating over members (also supplied), and handling of type mismatching (which could be done in c++03), and bob is your uncle.
C++ gives compile time reflection primitives; so you have to write the glue code yourself as far as I am aware.
I would start with a function making a tuple of (name member pointer) pairs using reflection. It can be pure constexpr
.
Then another function that does setting based on that structure, where runtime failure is in play.
That will let you unit test both pieces seperately; only the building of the "dictionary" requires reflection.