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

// ALLOW_PRIVATE_REFLECTION
#include <reflection.hpp>
class Mammal
{
public:
  int age;
};

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

  int GetAge();
};

// mammals.cpp

...
// Define the Mammal class for reflection
DEFINE_TYPE(reflection_example::Mammal)
{
  // Define its age member
  DEFINE_MEMBER(age);
}

DEFINE_TYPE(reflection_example::Human)
{
  // Declare that we have a parent class
  // Note that this also declares Human a child of Mammal
  DEFINE_PARENT(reflection_example::Mammal);

  // Declare Human's members
  DEFINE_MEMBER(name);
  DEFINE_MEMBER(children);

  // Since the class definition allows private reflection, we can get Mammal::Age
  DEFINE_MEMBER(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 *