Reflection is a very useful tool and if you aren’t familiar with the state of affairs in simple C++.
The cmake-reflection-template repository is a small working example of a few source files with added reflection which generates serialization and deserialization routines (using std::any<> for simplicity – so it requires C++17 – but it can be rewritten to serialize to JSON instead).
- Each CMake target that wants to have reflection should have the target_parse_sources() CMake function called on it like so
- Each source file in the reflected projects has an attached custom CMake command so when it gets modified that command gets ran
- That command runs the parser on the file – named for example my_type.h – which generates code and dumps it in a file called my_type.h.inl in a gen folder inside CMAKE_BINARY_DIR
- The resulting my_type.h.inl can be included either directly in my_type.h or perhaps elsewhere – the forward declarations of the generated functions are written inside the classes in my_type.h using the helper FRIENDS_OF_TYPE(MY_TYPE); macro.
It is a bit like what Unreal is doing for reflection of properties – C++ source code is parsed (and annotated with preprocessor identifiers) and each source file includes the generated code for itself.