开发者

Parameters in c++ templates

Function template example

template<typename T, int n>
T max(T (&arr)[n])
{
   T maxm = arr开发者_Python百科[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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜