I tried to write a function to sum the items inside an array:
template <class T, size_t N>
T sumItems(T (&arrayOfInt)[N]) {
int sum = 0;
for (int i = 0; i < N; i++) {
sum += arrayOfInt[i];
}
return sum;
}
And I call it like this:
int main(int argc, const char * argv[]) {
cout << "Plese enter the number of elements: ";
int numOfElements;
cin >> numOfElements;
int arrayOfInts[numOfElements];
for (int i = 0; i < numOfElements; i++) {
cin >> arrayOfInts[i];
}
int sum = sumItems(arrayOfInts);
cout << sum << endl;
return 0;
}
The compiler told me "there is no matching function for call to 'sumItems'". However, if I change
int arrayOfInts[numOfElements];
to
int arrayOfInts[5];
The code works without problem.
I know there should be some better solutions to do this (like using vector instead of array). But I'd like to know why it has such a behaviour and how to avoid that.
Thanks in advance!