9

I'm trying to understand the template function. The ultimate goal is to pass an entire array to a function. There seem to be many different ways to implement this but they all use the template function. Here's one of the simpler examples I've found...

template<size_t N>
void h(Sample (&arr)[N])
{
    size_t count = N; //N is 10, so would be count!
    //you can even do this now:
    //size_t count = sizeof(arr)/sizeof(arr[0]);  it'll return 10!
}
Sample arr[10];
h(arr); //pass : same as before!

I thought template<> was used to create a variable that could be used in place of int, float, char, etc.. what's the point of specifying the type (size_t), what does this do?

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
Ben Marconi
  • 161
  • 1
  • 1
  • 7

2 Answers2

3

The size_t N template parameter is a deduced integral value based upon the array size passed to the template function. Templates parameters can be

  • non-type template parameter;
  • type template parameter;
  • template template parameter.

Reference: Template Parameters.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
ThomasMcLeod
  • 7,603
  • 4
  • 42
  • 80
-1

You can reuse the template for arrays of any size.