abraham_hilbert abraham_hilbert - 10 months ago 53
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
. Here, I want foo to have the return type
(which is no problem) and as input, I will pass N-times the type
but I don't know how. Is there any possibility?

Many thanks in advance.

Answer Source

You can use std::index_sequence:

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...>> {
    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>> {};