c++ - template specialization call by reference -
to understand more c++ templates, reading book (c++ templates : complate guide) , can't understand explanation.
// basics/max3a.cpp #include <iostream> #include <cstring> #include <string> // maximum of 2 values of type (call-by-reference) template <typename t> inline t const& max (t const& a, t const& b) { return < b ? b : a; } // maximum of 2 c-strings (call-by-value) inline char const* max (char const* a, char const* b) { return std::strcmp(a,b) < 0 ? b : a; } // maximum of 3 values of type (call-by-reference) 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 call-by-value } int main () { ::max(7, 42, 68); // ok const char* s1 = "frederic"; const char* s2 = "anica"; const char* s3 = "lucas"; ::max(s1, s2, s3); // error }
the book says,
" problem if call max() 3 c-strings, statement
return max (max(a,b), c);
becomes error. because c-strings, max(a,b) creates new, temporary local value may returned function reference.
"
i understand max(s1, s2, s3) called reference arguments, inside max-of-three function, max(a,b) using call-by-value function(because it's more speicialized). , temporary return value max(a,b) value(in stack) , there no max(value, reference) function. isn't problem? can't understand book's text saying ... becomes error. because c-strings, max(a,b) creates new, temporary local value may returned function reference
.
and temporary return value max(a,b) value(in stack)
no, return value not "in stack". it's value, period. full stop:
inline char const* max (char const* a, char const* b)
this returns value. in caller's context, it's temporary value. now, let's proceed next step:
return max (max(a,b), c); //
in template, return
returns reference. refence value returned call max()
, which, in context, temporary value.
this temporary value goes out of scope , gets destroyed when function call returns. does, , returns reference destroyed value. de-referencing reference becomes undefined behavior.
this has nothing templates, , specialization. true equivalent, non-template code.
Comments
Post a Comment