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

前端 未结 5 1988
臣服心动
臣服心动 2020-12-01 07:58

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

5条回答
  •  执念已碎
    2020-12-01 08:30

    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
    struct type_list
    {
      typedef Head head;
      typedef Tail tail;
    };
    
    struct null_type
    {};
    
    template
    struct list_head
    {
      typedef typename List::head head;
    };
    
    template
    struct list_tail
    {
      typedef typename List::tail tail;
    };
    
    template
    struct list_length
    {
      static const size_t length = 1+list_length< typename list_tail::tail >::length;
    };
    
    template<>
    struct list_length
    {
      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::length;
    
      list_head::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 > >
    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

提交回复
热议问题