Example 3


#include <iostream>
#include <complex>
namespace mySpace{ // getting sure that this is the class we call becouse std::max is implemented
    template < class T > // for any class/typename T
    inline const T& max (const T& a, const T& b){ //
        return a>b?a:b; // where the operator '>' is implemented
    }
}
int main(){
    std::cout << mySpace::max(10,20) << std::endl;// works perfectly as we saw
    //std::cout << mySpace::max(15,21.1) << std::endl;// error: no matching function for call to ‘max(int, double)’
    //std::cout << mySpace::max('a',21) << std::endl;// error: no matching function for call to ‘max(char, int)’
    
    //some ways to fix it:
    
    // static_cast is a powerful tool, and I'm going to explain it while course
    std::cout << mySpace::max(static_cast<double>(15),21.1) << std::endl;
    
    // double(x) call the costructor of double, so 15 is an double
    std::cout << mySpace::max(double(15),21.1) << std::endl;
    
    // this is a bad practice, this cast is highlighting to the compiler that is a double
    //in this case works, but take care it
    std::cout << mySpace::max((double)15,21.1) << std::endl;
    
    //and the first solucion where we really use templates
    //we are forcing that max's call have to be doouble
    std::cout << mySpace::max<double>(15,21.1) << std::endl;
    
    //this examples also works but returning types is unexpected
    //we unlike 97's answer, we wanted a, as char
    //but our template function is unable to do it
    std::cout << mySpace::max<int> ('a',21) << std::endl;
    
    //This works too but don't make much sense
    std::cout << mySpace::max(int('a'),21) << std::endl;
    return 0;
}
read more ->

No comments:

Post a Comment