Monday, February 13, 2012

Instantiation


Unfortunately, the tems instance and instantiate are used in a different context in object-oriented programming.
In general, when I speak about instantisate I will be refering at template context.

When we define a template, compiler review if the systax is correct but this isn't enough, for example, the example of max. We instantiated some calls to max with int, string, float. All examples worked well because each type had the operator > implemented, the review of this is what I call instantisate.

So, the instantiation is when compiler checks whether some calls like max(a,b) can make it. In the example you'll see below you can see when compiler make an error for instantisation because our template method is assuming we can use the operator > and isn't implemented.

Below an example where instantisate makes an error:


#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::complex<float> a(10,10.1);
    std::complex<float> b(10.1,10);
    
    std::cout << mySpace::max(a,b) << std::endl;
    
    return 0;
}

main.cpp: In function ‘const T& mySpace::max(const T&, const T&) [with T = std::complex]’:
main.cpp:13:34:   instantiated from here
main.cpp:6:22: error: no match for ‘operator>’ in ‘a > b’
Fixing this error:
#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
    }
    template<class T> 
    inline bool operator>(const std::complex<T>& a, const std::complex<T>& b)    {
        if(a.imag() > b.imag())
            return true;
        return false;
    }
}
int main(){
    std::complex<float> a(10,10.1);
    std::complex<float> b(10.1,10);
    
    std::cout << mySpace::max(a,b) << std::endl;
    
    return 0;
}
This solucions is prioritizing 'i' (complex number), but we could do anything.

Next topic, Argument Deduction.

Thanks you all.

No comments:

Post a Comment