简体   繁体   中英

Parameters in c++ templates

Function template example

template<typename T, int n>
T max(T (&arr)[n])
{
   T maxm = arr[0];
   for(int i = 1; i <n; ++i)
      if (maxm < arr[i])
       maxm = arr[i];

   return maxm;
}

Is arr also a type parameter like T ?

arr is a name of a function parameter. It's not a type parameter. Its type is a reference to an array of element type T and length n .

Is arr also a type parameter like T ?

No arr is a call parameter. It is neither a type parameter nor a non-type parameter

arr is a usual function parameter which is passed a variable when the function is called.

However, the type of that argument is used to determine T and n , which are template parameters. So in a way, arr is used to link the function argument to the template arguments.

This process is called type deduction .

arr is function parameter, which type is deduced from T and n .

Think about changing your code to:

template<typename T, int n>
T max(T (&arr)[n])
{
   T* maxel = &(arr[0]);
   for(int i = 1; i <n; ++i)
      if (*maxel < arr[i])
       maxel = &(arr[i]);

   return *maxel;
}

In your version if you'll gave some array of objects that are bigger as index rises every time copy ctor would be called - and that could be somehow expensive, depending of T type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM