Alex Rivera | Logout

C++ Template Metaprogramming - Is it possible to output the generated code?

Asked 2009-08-02T14:29:01.923
28

I would like to debug some templated code to understand it better.
Unfortunately I'm new to template metaprogramming and it IS hard for me to get in.

When I try to output the preprocessed source files I get 125 000 lines of code :/

So is there a way I can see the generated Code? (The library I'm using is SeqAn)

Edit
Report

2 Answers

24

No it isn't. The preprocessor has nothing to do with template processing, which is performed by the compiler. Templates do not generate C++ code, any more than a function call does - they are an integral part of the C++ language itself.

answered 2009-08-02T14:31:40.170
1

at general it is not possible to output the entire code. But what I found extremely interesting, is the ability to use Visual C++ debugger to show you the type. Take that simple meta-program:

template<class Head, class Tail>
struct type_list
{
  typedef Head head;
  typedef Tail tail;
};

struct null_type
{};

template<class List>
struct list_head
{
  typedef typename List::head head;
};

template<class List>
struct list_tail
{
  typedef typename List::tail tail;
};

template<class List>
struct list_length
{
  static const size_t length = 1+list_length< typename list_tail<List>::tail >::length;
};

template<>
struct list_length<null_type>
{
  static const size_t length = 0;
};


int main()
{
  typedef 
    type_list
    < int
    , type_list
      < double
      , type_list
        < char
        , null_type
        >
      >
    >       my_types;

  my_types test1;

  size_t length=list_length<my_types>::length;

  list_head<list_tail<list_tail<my_types>::tail>::tail>::head test2;

}

I just instantiated my meta-types. These are still empty C++ class instances which are at least 1 byte long. Now I can put a breakpoint after the last instantiation of test2 and see, which types/values length, test1 and test2 are of:

Here is what the debugger shows:

length  3   unsigned int
test1   {...}   type_list<int,type_list<double,type_list<char,null_type> > >
test2   -52 'Ì' char

Now you you know the head returned you a character, your list contains int, double, char and is terminated by null_type.

That helped me a lot. Sometimes you need to copy the really messy type to a text editor and format it to a readable form, but that gives you the possibility to trace what is inside and how it is calculated.

Hope that helps,
Ovanes

answered 2009-08-02T16:16:44.830

Your Answer