Reflection in standard C++

I've been playing with C++ a lot lately, trying to see what ways I can manipulate templates and macros.  I'm aware that it isn't a wholly original concept, but today I decided it would be a good idea to try implementing a nice reflection interface for C++.  Right now it only supports members and parent/child relationships.  The next step is to implement method metadata, and eventually I'd like the system to be extensible such that you can attach arbitrary metadata to classes and their members.

Here's an example class definition from the git repo:

// mammals.h

#include <reflection.hpp>
class Mammal
  int age;

class Human : Mammal
  // Declare that the reflection system can access
  // private members
  std::string name;
  std::vector<Human> children;

  int GetAge();

// mammals.cpp

// Define the Mammal class for reflection
  // Define its age member

  // Declare that we have a parent class
  // Note that this also declares Human a child of Mammal

  // Declare Human's members

  // Since the class definition allows private reflection, we can get Mammal::Age

As you can see, all it takes to reveal a class to the reflection library is to list the names of the members you want it to see, and it automagically does the rest.  Pretty nifty, huh?

All of the code is available at here as a header-only library.  Feel free to use it and contribute if you want.

Leave a Reply

Your email address will not be published. Required fields are marked *