Overloaded template parameters - why is this example a problem?

I started reading C ++ Templates - the complete guide to Josuttis and Vandevoorde. And my tiny mind is stuck.

The authors state that "you must limit your changes to the number of parameters or explicitly specify the template parameters", using this as an example that causes problems:

template <typename T>
inline T const& max (T const& a, T const& b)
{
    return a < b ? b : a;
}

// maximum of two C-strings
inline char const* const& max( char const* a, char const* b)
{
    return std::strcmp(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);
}

It is said that using the 3 argument max version is a mistake -

const char * s1 = "fred";
const char * s2 = "anica";
const char * s3 = "lucas";
::max(s1, s2, s3); // ERROR

"because it max(a,b)creates a new temporary local value for C-lines , which can be returned by function by reference.". But I compiled and had a great time.

Can someone explain what the author says in this example?

+3
source share
4

, " C-" ​​ , . - " " ( , , , ).

, const char* :

char const* const& max( char const* const& a, char const* const& b)

, , , , max ( , max(a,b) max(max(a,b),c)), undefined ( ).

+3

a b . , , .

+1

max, C-,

inline char const* max( char const* a, char const* b)
{
    return std::strcmp(a, b) < 0 ? b : a;
}

Thus, the call max(a,b)inside is max(max(a,b),c)not the culprit. This is due to the fact that it is max(max(a,b),c)allowed with overloading to max( char const* a, char const* b)where it atakes a return value max(a,b). But this function returns a value, and the value 3-arg maxreturns a reference ; therefore a mistake.

0
source

Source: https://habr.com/ru/post/1772564/


All Articles