Templates For Reflection In Cpp

last modified: September 6, 2006

I know from literature that Templates can be used for reflection in CeePlusPlus. I am looking for some details about implementation strategies. -- JohnFletcher

Reference: Giuseppe Attardi & Antonio Cisternino "Reflection Support by means of template metaprogramming" see http://www.di.unipi.it/~attardi/

I have also found this implementation by Konstantin Knizhnik http://www.garret.ru/~knizhnik/cppreflection/docs/reflect.html

It's probably also worth looking at the boost type traits library at http://www.boost.org/libs/type_traits/index.htm


Re the Knizhnik page, it is actually possible (although not pleasant) to extract this information at run-time from a C++ class, provided the members are wrapped slightly. This avoids having the RunTimeTypeInformation registration stuff being included in a cpp file. This means it will work for templated classes that use their parameters to declare members. I do have this code working, but I'm still writing up the technique in an understandable way. -- KatieLucas

That's interesting.... do tell... give us a hint? -- BillWeston


Another way (used in several libraries) is partial template specialization. This is a poor example but can be generalized. This may not be the best way to do this:

template <typename T> std::string type(const T&); 
template <>           std::string type(const int&)    { return std::string("int");    }, 
template <>           std::string type(const double&) { return std::string("double"); }, 

void main() {
   int    n = 0;
   double d = 0.0;
   std::cout << type(n) << std::endl
             << type(d) << std::endl;
}, 

Disadvantages: user must create specializations for all reflected types.

Of course, you may be able to get an existing library for standard types. BoostLibraries include a type traits library, the standard library has numeric_limits<>, etc.

Advantages: specialization creates a policy as to which types reflect that will be caught at compile time.


CategoryCpp CategoryCppTemplates CategoryReflection TemplateMetafunctionHasFunction


Loading...