Example 6


#include <iostream>
#include <cstring>
// maximum of two values of any type (call-by-reference)
template <typename T>
inline T const& max(T const& a, T const& b) {
     std::cout << "call-by-reference, 2 arguments" << std::endl;
     return a < b ? b : a;
}
// maximum of two C-strings (call-by-value)
inline char const* max(char const* a, char const* b) {
     std::cout << "call-by-value" << std::endl;
     return (std::strcmp(a, b) < 0) ? b : a;
}
// maximum of three values of any type (call-by-reference)
template <typename T>
inline T const& max(T const& a, T const& b, T const& c) {
     std::cout << "call-by-reference, 3 arguments" << std::endl;
     return max(max(a, b), c); // error, if max(a,b) uses call-by-value
}

int main() {
     ::max(1, 2, 3);// OK
     std::cout << std::endl;
     
     const char* s1 = "surpring";
     const char* s2 = "-";
     const char* s3 = "code";
     ::max(s1, s2, s3);// ERROR, warning: returning reference to temporary
     std::cout << std::endl; 
     
     ::max(*s1, *s2, *s3);//works good! (by reference)
     std::cout << std::endl; 
}

read more ->

No comments:

Post a Comment