How can I generate a tuple of N type T's?

后端 未结 3 1631
再見小時候
再見小時候 2020-12-19 14:28

I want to be able to write generate_tuple_type which would internally have a type alias type which would be std::tuple

3条回答
  •  粉色の甜心
    2020-12-19 15:00

    Fairly straightforward recursive formulation:

    template
    struct generate_tuple_type
    {
     typedef typename generate_tuple_type::type type;
    };
    
    template
    struct generate_tuple_type
    {
      typedef std::tuple type;
    };
    

    Live example

    [Update]

    OK, so I was only thinking about modest values of N. The following formulation is more complex, but also significantly faster and less compiler-crushing for large arguments.

    #include 
    
    template
    struct join_tuples
    {
    };
    
    template
    struct join_tuples, std::tuple>
    {
      typedef std::tuple type;
    };
    
    template
    struct generate_tuple_type
    {
      typedef typename generate_tuple_type::type left;
      typedef typename generate_tuple_type::type right;
      typedef typename join_tuples::type type;
    };
    
    template
    struct generate_tuple_type
    {
      typedef std::tuple type;
    };
    
    template
    struct generate_tuple_type
    {
      typedef std::tuple<> type;
    };
    
    int main()
    {
      using gen_tuple_t = generate_tuple_type::type;
      static_assert( std::tuple_size::value == 30000, "wrong size" );
    }
    

    Live example

    This version performs at most 2*log(N)+1 template instantiations, assuming your compiler memoizes them. Proof left as an exercise for the reader.

提交回复
热议问题