Search code examples
c++templatesvariadic-templatestemplate-meta-programming

Concatenate two typed variadic template packs


Consider this struct

template<std::size_t... a>
struct A{};

How can I concatenate two typed variadic template arguments?

concat<A<1,2,3>, A<4,5,6,7>> // should be of type A<1,2,3,4,5,6,7>

Solution

  • You can implement this with a specialization that handles instantiations of A.

    template<typename...>
    struct concat_impl;   // just a declaration, to allow for specializations
    
    template<std::size_t... s1, std::size_t... s2>
    struct concat_impl<A<s1...>, A<s2...>> {        // specialize   
        using type = A<s1..., s2...>;               // concatenate
    };
    

    and a convenience alias to avoid having to say typename everywhere.

    template<typename A1, typename A2>
    using concat = typename concat_impl<A1,A2>::type;
    

    Here's a demo