I have a custom array class
template <typename T, unsigned L>
class Array
{
T m_buff[L];
};
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)
.
CodePudding user response:
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
/