Search code examples
c++templatesc++14std-function

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.


Solution

  • You can use std::index_sequence:

    template<std::size_t N, typename = std::make_index_sequence<N>>
    struct A;
    
    template<std::size_t N, std::size_t... S>
    struct A<N, std::index_sequence<S...>> {
        std::function<std::size_t(decltype(S)...)> foo;
    };
    

    Live example

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

    template<typename T, std::size_t N, typename = std::make_index_sequence<N>>
    struct A;
    
    template<typename T, std::size_t N, std::size_t... S>
    struct A<T, N, std::index_sequence<S...>> {
        template<std::size_t>
        using type = T;
    
        std::function<std::size_t(type<S>...)> foo;
    };