abraham_hilbert abraham_hilbert - 18 days ago 6
C++ Question

Expand a type N times in template parameter

I have the following problem:

template< std::size_t N >
class A
{
std::function< std::size_t( /*std::size_t,....,std::size_t <- N-times*/) > foo;
};


As you can see above, I try to declare an
std::function<...> foo
as a member of a class
A
. Here, I want foo to have the return type
std::size_t
(which is no problem) and as input, I will pass N-times the type
std::size_t
but I don't know how. Is there any possibility?

Many thanks in advance.

Answer

You can use std::index_sequence:

template<typename>
struct AHelper;

template<std::size_t... S>
struct AHelper<std::index_sequence<S...>> {
    std::function<std::size_t(decltype(S)...)> foo;
};

template<std::size_t N>
struct A : AHelper<std::make_index_sequence<N>> {};

Live example at coliru

If you like, you could also define to what type it expands:

template<typename, typename>
struct AHelper;

template<typename T, std::size_t... S>
struct AHelper<T, std::index_sequence<S...>> {
    template<std::size_t>
    using type = T;

    std::function<std::size_t(type<S>...)> foo;
};

template<typename T, std::size_t N>
struct A : AHelper<T, std::make_index_sequence<N>> {};