Saturday, December 10, 2011

An Improvement of C++ Typelists



Overview
        I was deeply impressed by the dramatic code of “Modern C++ Design: Generic Programming and Design Patterns Applied” when I read it about four years ago. However, there are some imperfection of the solution to typelists . One is that the linearizing typelist creation requires a plethora of macros. Another one is that the template generating a typelist cannot be viewed as a typelist directly. The result should be retrieved by some nested type of the template class. The last one is that the generating hierarchies store the objects as a member rather than inheritance, which hides the interface of the type in typelist. Hence, I implement another typelist avoiding such imperfections. You can get it here. A compiler with C++11 support(e.g. GCC 4.6.2) is needed.



Typelist Creation
        This problem can be easy solved by using new C++ feature, variadic templates. Transforming a parameter pack to a typelist is trivial. But putting all types in a typelist into a parameter pack is not intuitive. The key is writing a template which takes a typelist and a parameter pack as template parameters. When we pick a type from the typelist, we insert it to the parameter pack at the same time. Unlike general definition of variadic template, the size of parameter pack will increase as stepping deeper.


Type Retrievement
        The reason why we cannot retrieve the result without nested type is that the template class is not a typelist class. Or, more accurately, the behavior of the template class is not the same as typelist. In Andrei Alexandrescu’s book, a typelist should be a class generated by the template Typelist. This can be fix by relaxing the restriction. In my implementation of typelists, any class that has nested types “head” and “tail” can be used as typelist. By this definition, if a class inherits a typelist, then it is a typelist. Moreover, we gain another benefits: we can easily write a manipulation template by inheriting certain typelist without a mass nested types.


Generating Hierarchies
        Because the instance of a type is store as a member, we cannot access its interface directly. By letting the Holder class inherit the type in typelist, we will obtain a class that has all the interfaces of the types. Except reducing the typing work, it can be used as the framework of powerful Mixins and enable Empty Base Optimization.

No comments:

Post a Comment