Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function with a size_t Template Parameter

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?

like image 379
Ben Marconi Avatar asked Jan 23 '16 20:01

Ben Marconi


1 Answers

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.

like image 155
ThomasMcLeod Avatar answered Oct 15 '22 01:10

ThomasMcLeod