Search code examples
c++c++17variadic-templatestemplate-meta-programmingstdtuple

How to create a tuple of fix types whose size is a known at compile time in C++17?


I would like to create a tuple type of common element type whose length is known at compile time. For example if I have

static constexpr const std::size_t compiletime_size = 2;

using tuple_int_size_2 = magic (int, compiletime_size);

tuple_int_size_2 should be the same type as std::tuple<int, int>


Solution

  • This can be done with recursion:

    #include <tuple>
    
    template <size_t N, typename Head, typename... T>
    struct magic {
        using tuple_type = typename magic<N - 1, Head, Head, T...>::tuple_type;
    };
    
    template <typename... T>
    struct magic<1, T...> {
        using tuple_type = std::tuple<T...>;
    };
    
    int main()
    {
        auto t = typename magic<3, int>::tuple_type{};
        return 0;
    }
    

    I wonder, though, if std::array would be a much simpler and straight-forward solution to whatever task it is you're trying to solve.