| re: Doubt in C++ Templates - Josuttis.
"SK" <sk_ind12@rediffmail.com> wrote...[color=blue]
> I have a doubt in C++ Templates by Nicolai M. Josuttis.[/color]
Wow, a double in an entire book after reading mere 17 pages?
[color=blue]
> On Page 17 there is a line "In general, it is a good idea not to
> change more than necessary when overloading function templates. You
> should limit your changes to the number of parameters or to specifying
> template parameters explicitly."
>
> Can anyone explain the meaning of these lines to me?[/color]
If you change too much, you muddy the _reason_ for overloading.
Besides you may run into problems similar to what they describe
in the comment: the error is due to the fact that some functions'
parameter passing method is different.
[color=blue]
> Also the example quoted is -
>
> template<typename T>
> inline T const& max (T const& a, T const& b)
> {
> return a < b ? b : a;
> }
>
> inline T const& max (char const* a, char const* b)[/color]
You could at least give the author the respect of quoting right.
Actually, it's
inline char const* max(char const* a, char const* b)
[color=blue]
> {
> return stdcmp(a, b) < 0 ? b : a;
> }
>
> template<typename T>
> inline T const& max (T const& a, T const& b, T const& c)
> {
> return max (max(a, b), c); // Error, if max(a, b) uses pass by value[/color]
The comment should probably say
// Error if max(a,b) _returns_ a temporary by value
[color=blue]
> }
>
>
> The reason for error given is that because for C-strings, max(a, b)
> creates a new, temp local value that MAY be returned by the function
> by reference.
> I have also not been able to understand the reason for error given by
> him.[/color]
In max(a,b,c) all arguments are _references_. Now, if 'max(a,b)'
returns by value (when a, b, and c are char const*), the returned
value is a temporary char const*. In order to call the next 'max'
a _reference_ to that temporary has to be created and _can_ be
returned from the function (since max(a,b,c) returns by reference).
That's an error.
Victor |