Search code examples
c++c++11template-meta-programmingstdtuple

Produce std::tuple of same type in compile time given its length by a template argument


In c++, how can I implement a function with an int template argument indicating the tuple length and produce a std::tuple with that length?

E.g.

func<2>() returns std::tuple<int, int>();
func<5>() returns std::tuple<int, int, int, int, int>().

Solution

  • Here is a recursive solution with alias template and it's implementable in C++11:

    template <size_t I,typename T> 
    struct tuple_n{
        template< typename...Args> using type = typename tuple_n<I-1, T>::template type<T, Args...>;
    };
    
    template <typename T> 
    struct tuple_n<0, T> {
        template<typename...Args> using type = std::tuple<Args...>;   
    };
    template <size_t I,typename T>  using tuple_of = typename tuple_n<I,T>::template type<>;
    

    For example if we want "tuple of 3 doubles" we can write:

    tuple_of<3, double> t;