James Mitchell
James Mitchell

Reputation: 315

How do I generate a variadic parameter pack?

Is it possible to generate a non-type parameter pack given an unrelated input? What I mean is, I would like like to turn this:

template <typename D, size_t... Offsets> struct VecGeneric;
template <typename N, size_t C> struct VecGenericData;

template <typename N, size_t D> struct TVecN;
template <typename N> struct TVecN<N,2> : public VecGeneric<VecGenericData<N,2>,0,1>           { };
template <typename N> struct TVecN<N,3> : public VecGeneric<VecGenericData<N,3>,0,1,2>         { };
template <typename N> struct TVecN<N,4> : public VecGeneric<VecGenericData<N,4>,0,1,2,3>       { };
template <typename N> struct TVecN<N,5> : public VecGeneric<VecGenericData<N,5>,0,1,2,3,4>     { };
template <typename N> struct TVecN<N,6> : public VecGeneric<VecGenericData<N,6>,0,1,2,3,4,5>   { };
template <typename N> struct TVecN<N,7> : public VecGeneric<VecGenericData<N,7>,0,1,2,3,4,5,6> { };
// ...

Into something like this:

template <typename D, size_t... Offsets> struct VecGeneric;
template <typename N, size_t C> struct VecGenericData;

template <typename N, size_t D> struct TVecN : public VecGeneric<VecGenericData<N,D>,IntPack<D>...> { };

Upvotes: 2

Views: 289

Answers (1)

dyp
dyp

Reputation: 39111

Constructing the integer sequence 0,1,2,...,N-1 given N is typically done recursively; for example:

template<size_t... Is> struct index_sequence {};

namespace detail
{
    template<size_t N, size_t... Is>
    struct make_index_sequence_h
        : make_index_sequence_h<N-1, N-1, Is...>
    {};

    template<size_t... Is>
    struct make_index_sequence_h<0, Is...>
    {
        using type = index_sequence<Is...>;
    };
}

template<size_t N>
using make_integer_sequence = typename detail::make_integer_sequence_h<N>::type;

(À la C++1y StdLib)

To use these integers, you deduce them from the index_sequence type:

namespace detail
{
    template<typename N, class IndexSequence>
    struct helper;

    template<typename N, size_t... Is>
    struct helper<N, index_sequence<Is...>> // deduce the integers
    {
        using type = VecGeneric<VecGenericData<N, sizeof...(Is)>, Is...>;
    };
}

The above is a metafunction that will "compute" the type you want to derive from. Simplify the usage using an alias template:

namespace detail
{
    template<typename N, size_t D>
    using helper_t = typename helper<N, make_index_sequence<D>>::type;
}

The result:

template <typename D, size_t... Offsets> struct VecGeneric
{
    // just a quick test:
    void print()
    {
        std::cout << __PRETTY_FUNCTION__ << "\n";
    }
};

template <typename N, size_t C> struct VecGenericData {};

template <typename N, size_t D> struct TVecN : public detail::helper_t<N, D> {};

int main()
{
    TVecN<int, 5>().print();
}

Upvotes: 7

Related Questions