0

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.

Andreas H.
  • 5,557
  • 23
  • 32
  • Are you asking if this is supported in the TS, or if it can be done with the current standard? For the latter, this is a dupe https://stackoverflow.com/questions/41453/how-can-i-add-reflection-to-a-c-application – cigien Mar 14 '21 at 14:01
  • Yes it is possible. – Yakk - Adam Nevraumont Mar 14 '21 at 14:31
  • @cigien I am asking only about the TS. – Andreas H. Mar 14 '21 at 16:30
  • @Yakk-AdamNevraumont When I look into the TS I find most of the functions are named 'get_XX' (like `get_type`, `get_scope`, ...) or 'is_XXX' (like `is_private`, ...) which seems to me to give only 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 how this is supposed to be done in the TS are welcome. – Andreas H. Mar 14 '21 at 18:47

1 Answers1

1

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 ), 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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • I guess, that makes sense. So member access is supported indirectly via given pointer (to member). That pretty much answers it. – Andreas H. Mar 14 '21 at 19:34