Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
abraham_hilbert Avatar asked Oct 12 '16 09:10

abraham_hilbert


People also ask

What is template type parameter?

A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

What does template <> mean in C++?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

Which template can have multiple parameters?

C++ Templates: Templates with Multiple Parameters | C++ Tutorials for Beginners #65.

Which parameter is allowed for non-type template?

Which parameter is legal for non-type template? Explanation: The following are legal for non-type template parameters:integral or enumeration type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer to member.


2 Answers

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(decltype(S)...)> foo;
};
like image 84
Guillaume Racicot Avatar answered Oct 31 '22 05:10

Guillaume Racicot


For arbitrary type and not just size_t, just write a helper alias:

template<class T, size_t>
using Type = T;

template<std::size_t... S>
struct AHelper<std::index_sequence<S...>> {
    std::function<size_t(Type<MyArbitraryTypeHere, S>...)> foo;
};
like image 3
T.C. Avatar answered Oct 31 '22 05:10

T.C.