8

Basic question here, with (hopefully) a simple answer: I'm trying to write a function whose first argument is a std::array, but with an arbitrary size.

void f(array<int> x) {
    //do stuff
}

isn't valid, because I need a size for array<int, #>. Is there a way to get around this?

CSGregorian
  • 134
  • 1
  • 7

3 Answers3

12

The only way is to make f a function template :

template <size_t N>
void f(array<int, N> x) {
    //do stuff
}
Quentin
  • 62,093
  • 7
  • 131
  • 191
12

Quentins answer is correct if you do not need to be flexible at run-time.

However, if you need to be flexible at run-time I would recommend you to use an std::vector instead.

void f(vector<int> x) {
    //do stuff
}

Also, you might want to use a reference or const reference to avoid the copying of the array or vector, at least if you do not need the copy.

Community
  • 1
  • 1
Theolodis
  • 4,977
  • 3
  • 34
  • 53
5

A second way around it, is using the function template (@Quentin) and delegate to a non template function:

#include <array>

void g(int* first, int* last) {
    //do stuff
}

template <size_t N>
inline void f(std::array<int, N> x) {
    g(x.begin(), x.end());
}
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
  • 1
    And what is the concrete benefit of the non template function? – Theolodis Jul 10 '14 at 17:39
  • 2
    @Theolodis: The implementation can be in a source file. –  Jul 10 '14 at 17:42
  • 1
    @Theolodis _'And what is the concrete benefit ...?'_ The non template function is a bit more generic, and no longer depends on the compile time provided `size_t N`. – πάντα ῥεῖ Jul 10 '14 at 18:04
  • @πάνταῥεῖ ok, I didn't think of that... Actually it could even be used with the vector solution I proposed too. – Theolodis Jul 10 '14 at 18:08
  • @Theolodis _'Actually it could even be used with the vector solution ...'_ Yup, exactly. You've got the point. The `std::vector` variant could be even a specialization for `N=0` or so. – πάντα ῥεῖ Jul 10 '14 at 18:20
  • 1
    Or you could just call `g()` directly without bothering with `f()`. :) – ppl Jul 10 '14 at 21:05