S
SK
Hi all,
I have a doubt in C++ Templates by Nicolai M. Josuttis.
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?
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)
{
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
}
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.
Thanks and regards,
SK
I have a doubt in C++ Templates by Nicolai M. Josuttis.
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?
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)
{
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
}
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.
Thanks and regards,
SK