Screenshot instructions:
Windows
Mac
Red Hat Linux
Ubuntu
Click URL instructions:
Right-click on ad, choose "Copy Link", then paste here →
(This may not be possible with some types of ads)
From: Greg Chicares <gchicares@sb...> - 2007-11-26 04:45:47
|
On 2007-11-25 17:36Z, John Brown wrote: [...] > /* 09 */ template <class T> > /* 10 */ T range_sum(T a[], int beg, int end, T initial=T()) > /* 11 */ { > /* 12 */ T sum = 0; > /* 13 */ for (int i=beg; i<=end; i++) > /* 14 */ sum += a[i]; > /* 15 */ return sum + initial; > /* 16 */ } > /* 17 */ > /* 18 */ // explicit instantiation What follows is an explicit specialization, not an explicit instantiation. These would be explicit instantiations: template int range_sum(int a[], int beg, int end, int initial); template double range_sum(double a[], int beg, int end, double initial); > /* 19 */ template <> > /* 20 */ int range_sum(int a[], int beg, int end, int initial=int()) > /* 21 */ { > /* 22 */ int sum = 0; > /* 23 */ for (int i=beg; i<=end; i++) > /* 24 */ sum += a[i]; > /* 25 */ return sum + initial; > /* 26 */ }; Stray semicolon on line 26, BTW. > When I compile this, I get: > 06-RangeSum.cpp:20: error: default argument specified in explicit specialization I believe the operative rule is 14.7.3/21: "Default function arguments shall not be specified in [...] the explicit specialization of a function template" > My questions: > > 1) I understand that when you write an explicit specialisation, you are supposed > to write 'template<> ...' and not, for example 'template<int> ..., but I > tried it. That is, I changed lines 19 and 29 to 'template' and 'template > respectively. The error at line 20 went away, but the error at line 30 > remained. The error also goes away if I set T = char. However, double and > float give the 'default argument' error. Why is this? I'm guessing that "hotmail" altered that text, and that you actually changed those lines to look like this: /* 19 */ template<int> /* 29 */ template<double> Those would define new and different function templates, with non-type arguments. The first is syntactically valid, but it almost certainly doesn't do what you want. The second isn't valid because a non-type argument can't be a double [14.3.2/1], and would have given a different error message, e.g. `double' is not a valid type for a template constant parameter at least if you got rid of the default argument. > 2) If I do not provide any explicit specialisations, the program will > compile and produce the expected output: > > 12 > 12.00 > > So why does it complain when I provide them? Just because the default arguments were respecified. But what are you trying to accomplish here? Why define partial specializations that just repeat the generic code, plugging in a particular type? The point of C++'s template facility is that the compiler does that for you. And why not just use std::accumulate() instead of writing this function template at all? |