T sqrt(T ); template c...">

C ++ template function overload

Below are the lines from the "C ++ programming language"

template<class T > T sqrt(T );
template<class T > complex<T> sqrt(complex<T>);
double sqrt(double);
void f(complex<double> z )
{
s q r t (2 ); // sqrt<int>(int)
sqrt(2.0) ; // sqrt(double)
sqrt(z) ; // sqrt<double>(complex<double>)
}

I do not understand why sqrt (z); calls sqrt<double>(complex<double>)can explain any body.

The author says T sqrt<complex<T>>more specialized than T sqrt <T>, but there is a separate ad for template<class T > complex<T> sqrt(complex<T>);, why not use it?

+3
source share
2 answers

Well, the function used is the one you are talking about sqrt<double>(complex<double>)- this is an instance of the template template <class T> complex<T> sqrt(complex<T>).

Your misunderstanding was in the meaning of the instance of the template, and not in the process of overloading.

+2
source

Looking back, it would be easier if Bjarn wrote this as

template<class T> T sqrt(T);
template<class U> complex<U> sqrt(complex<U>);
double sqrt(double);
void f(complex<double> z )
{
    sqrt (2); // sqrt<int>(int)
    sqrt(2.0) ; // sqrt(double)
    sqrt(z) ; // sqrt<double>(complex<double>)
}

. ; ++ . . ( ), . T = complex U = double. ? , , . , U T=complex<U>, .

+6

Source: https://habr.com/ru/post/1698471/


All Articles