#include <iostream>
#include <cstring>
#include <string>
namespace mySpace{
template < class T >
inline const T& max (const T& a, const T& b){
std::cout << "template"<< std::endl;
return a>b?a:b;
}
template < class T >
//I have changed the argument types to constants because I want to pass it by reference, (&)
//note that const T& is equivalent to T const&
inline T* const& max (T* const& a, T* const& b){
std::cout << "template pointer: "<< std::endl;
return a>b?a:b;
}
/*
* Note: Go back and remember the first template max; I didn't
* show any call like max("abc","acd"), this one is deduced as
* a char*, so, with the implementations we did (return a>b?a:b;),
* this operacion is comparing the pointers and no his values
* so this was a bug
*
* In order to resolve it, we may call max<std::string>("abc","acd")
* or calling constructor like std::string: max(std::string("abc"),std::st * ring("acd") )
*
* Or with the following function
*/
inline char const* const& max (char const* const& a, char const* const& b){
std::cout << "c-string: "<< std::endl;
return (std::strcmp(a,b) < 0) ? b : a;
}
}
int main(){
int a = 5, b = 10;
int* p_a = &a;
int* p_b = &b;
mySpace::max(a,b); mySpace::max(p_a,p_b); mySpace::max(*p_a,*p_b);
char const* s2 = "I'm so cool";
char const* s1 = "David";
mySpace::max(s1,s2); mySpace::max<>(s1,s2); mySpace::max("asd","asdasd");
std::string s3 = "David";
std::string s4 = "I'm so cool";
mySpace::max(s3,s4);
char* s5 = "David"; char* s6 = "I'm so cool";
mySpace::max(s5,s6);
return 0;
}
read more ->
No comments:
Post a Comment