Question

Looking at Java and C# they manage to do some wicked processing based on special languaged based anotation (forgive me if that is the incorrect name).

In C++ we have two problems with this:

1) There is no way to annotate a class with type information that is accessable at runtime.
2) Parsing the source to generate stuff is way to complex.

But I was thinking that this could be done with some template meta-programming to achieve the same basic affect as anotations (still just thinking about it). Like char_traits that are specialised for the different types an xml_traits template could be used in a declaritive way. This traits class could be used to define how a class is serialised/deserialized by specializing the traits for the class you are trying to serialize.

Example Thoughs:

template<typename T>
struct XML_traits
{
    typedef XML_Empty   Children;
};

template<>
struct XML_traits<Car>
{
    typedef boost::mpl::vector<Body,Wheels,Engine>   Children;
};

template<typename T>
std::ostream& Serialize(T const&)
{
    // my template foo is not that strong.
    // but somthing like this.
    boost::mpl::for_each<typename XML_Traits<T>::Children,Serialize>(data);
}
template<>
std::ostream& Serialize<XML_Empty>(T const&)
{ /* Do Nothing */ }

My question is:

Has anybody seen any projects/decumentation (not just XML) out there that uses techniques like this (template meta-programming) to emulate the concept of annotation used in languges like Java and C# that can then be used in code generation (to effectively automate the task by using a declaritive style).

At this point in my research I am looking for more reading material and examples.

Was it helpful?

Solution

Lately, I had a look at the following:

Have a good read :)

OTHER TIPS

There is a really good book on using the C++ template processor:

Andrei Alexandrescu Modern C++ Design Generic Programming and Design Patterns Applied Addison-Wesley, U.S.A., 2001 ISBN 0-201-70431-5

Andrei starts writing programs using C++ templates!

The template metaprogramming is a really powerful tool, but the thing is simple: your just have to invent your own additional syntax for describing properties.

Yes, parsing C++ is hard, but we only need the limited parsing capabilities: read the class list with hierarchy information and the list of all the serialized properties.

This can be done even in a C/C++ tool with a linear scanning algorithm, if we define some dummy macros.

Templates can abstract the class instantiation and on top of that we add the intrusive RTTI.

The complete description of the technique is described in my answer to this question

How to implement serialization in C++

Boost.Serialization is the answer. It introduces required portable RTTI for serialization custom types.

What about runtime reflection in C++ - it's a separate question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top