Building a compile time list incrementally in C++

后端 未结 3 1776
灰色年华
灰色年华 2021-01-06 10:30

In C++, is there a way to build a compile time list incrementally, in the following pattern?

START_LIST(List)
ADD_TO_LIST(List, int)
ADD_TO_LIST(List, float)         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 11:09

    You could use C++11 variadic templates directly, they allow to write typelists in a much more fancy way than the classic functional head:tail approach:

    template
    struct list{};
    
    using l = list;
    

    On the other hand, if you like the head-tail way you could translate from one format to the other. In this case (Variadic to functional):

    template
    struct list{};
    
    struct nil{};
    
    template
    struct make_list;
    
    template
    struct make_list
    {
        using result = list::result;
    };
    
    template<>
    struct make_list<>
    {
        using result = nil;
    };
    

    An example:

    //l is list>>
    using l = typename make_list::result;
    

    Of course you could use template aliases to make the syntax more clear:

    template
    using make = typename make_list::result;
    
    using l = make;
    

提交回复
热议问题