Mot
Mot

Reputation: 53

How do I pass std::array as a template parameter with a varying number of elements in C++?

I'm trying to make a template function that lets me use an std::array object as a parameter with a varying number of elements.

For example:

#include <array>

template <class T>
void func(std::array<T,/*varying#ofelems*/> ary){...}

Upvotes: 1

Views: 989

Answers (3)

jkerian
jkerian

Reputation: 17016

In most cases, I would recommend following the lead of the standard algorithms and taking two templated iterators for begin and end instead.

template <class InputIt>
void func(InputIt begin, InputIt end) {
    ...
}

Upvotes: 1

Marek R
Marek R

Reputation: 37647

The best way don't be to strict:

template <class T>
void func(const T& ary)
{
    ....
}

This way you will cover not only std::array, but also std::vector or other containers.

Upvotes: 2

KamilCuk
KamilCuk

Reputation: 140960

You just specify the number of elements inside the template parameters.

template<class T, size_t N>
void func(std::array<T, N> arr) {

}

Upvotes: 6

Related Questions