简体   繁体   中英

Function that takes templated length parameter

I have a custom array class

template <typename T, unsigned L>
class Array
{ ... };

My goal is to declare a function that would take a copy of the Array class and use its values to return a sum of all elements.
The problem is that the code compiles only for a function defined as int sum(Array<int, 3> a) and not for a function defined as int sum(Array<int> a) .

not for a function defined as int sum(Array a).

That's because Array<int> is not a valid type. Your Array template requires two parameters, not one.

What you are looking for, simply, is just another template function:

template<unsigned size> int sum(const Array<int, size> &a)
{
   // Function code here:
}

As far how to code it: simply think of what your code needs to be, in case of your Array<int, 3> , or, maybe, Array<int, 100000> and replace 3 or 100000 with size /

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