Why only double?
When we now try to use
sum0
,
we'll run into problems pretty soon:
double a[10];
float b[10];
// ...
double sa = sum0(a, 10); // OK
float sb = sum0(b, 10); // compile error
Unfortunately, sum0
works only with double
,
but not with float
arrays.
For this restriction,
there exists no substantial reason
—
except that for a normal C++ function, we have to fix a type
for each argument.
Type parameters
Now, if an argument type
could itself be a parameter,
then we could implement sum
once for
all value types of the array argument.
Such a type parameter can be specified using the C++ template syntax:
template<typename T>
T sum1(T* a, int n)
{
T res = 0;
for(int i = 0; i < n; ++i)
res += a[i];
return res;
}
The parameter T
takes over the role of the previously constant type double
,
and thus our call above now works:
double a[10];
float b[10];
int c[10];
// ...
double sa = sum1(a, 10); // OK
float sb = sum1(b, 10); // OK
int sc = sum1(c, 10); // OK
So, we can process array with arbitrary value type
(int
,
std::complex<double>
,
myvector
... if implemented reasonably),
or even std::string
(well, almost ... we'll come back to that).
So, are we now entirely happy?