0

I have this code snippet in C:

int foo[5];
int bar[10];

Func(foo, _countof(foo));  // (_countof(x) is the size of the array x)
Func(foo, _countof(bar));

void Func(int p[], int count)
{
  for (int i = 0; i < count; i++)
  {
    // do something with p[i]
  }
}

I need to translate this into C++

My first thought was something like this:

std::array<int, 5> foo;
std::array<int, 10> bar;

Func(foo, foo.size());
// or even better:
Func(foo); 

So far so good, but now I'm stuck with the Func function, I need to pass the std::array and the size, but std::array<int, 5> is not the same type as std::array<int, 10>.

void Func(std::array<int, ???> a, size_t count)
{

}

Is there an elegant way to solve this using std::array?

Do I need Func to be a function template?

I know how to do it with std::vector instead of std::array.

Peter Ruderman
  • 12,241
  • 1
  • 36
  • 58
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • make func a template that is parametrized on the number of elements? – 463035818_is_not_an_ai Nov 16 '18 at 20:56
  • 1
    Write a templated function. –  Nov 16 '18 at 20:56
  • If you are going for a template, consider making it a template which takes a pair of iterators, like the standard library algorithms (or use ranges rather than just arrays) – Justin Nov 16 '18 at 20:57
  • It's a pity that a duplicate only includes one of the very appealing solutions as the last answer with 0 score (until upvoted by me). Because of that, I am going to highlight it here - a good way of doing that is to use a `span` from C++20, or `gsl::span`. – SergeyA Nov 16 '18 at 21:10

0 Answers0