Search code examples
c++tuplesvariadic-templates

Parameterize of tuple with repeated type


I want to declare template:

template <size_t N, class Type> my_tuple
{
   using type = ... //something here
};

So that this my_typle<3, std::string>::type,for example, will be the same as this std::tuple<std::string, std::string, std::string> Please, show, how it can be done in one line, maybe, using std::index_sequence or something from boost or whatever? Or maybe it can not be done just simple?

UPD

Please, note I do not need an std::array, I need to parametrize some variable template with predefined list of types. I have used std::tuple as an example here.


Solution

  • This is fun. Here's a "pure" meta-programming approach to expand the sequence:

    template<typename T, typename Seq>
    struct expander;
    
    template<typename T, std::size_t... Is>
    struct expander<T, std::index_sequence<Is...>> {
        template<typename E, std::size_t>
        using elem = E;
    
        using type = std::tuple<elem<T, Is>...>;
    };
    
    template <size_t N, class Type>
    struct my_tuple
    {
       using type = typename expander<Type, std::make_index_sequence<N>>::type;
    };
    

    I say "pure" ironically. It's more akin to the classic meta-programming tricks, nothing else.