Function Template Overloading: An Example of Understanding Stroustrup

I looked through several threads with the same name as this, but I can not find anything that helped me figure this out ...

The following is an example of a small example from "C ++ Programming Language", second edition, B Stroustrup, section 13.3.2 (p. 336).

enter image description here

I do not understand the third permission overload sqrt(z). I expected a resolution to be sqrt<complex<double>>(complex<double>).

Obv function double sqrt(double)does not match the score. But I also thought that it template<class T>T sqrt(T)could not be allowed for sqrt<double>(complex<double>), because it seems to me that it implies that it Thas two different permissions, which I would think that this is impossible ... Tmust be the same throughout the "sphere "

Is there something that I misunderstood, and could you point out that? :) Thanks!

+4
source share
2 answers

The second is a specialty that is suitable for a challenge. The parameter T, i.e. Type in

complex<T>

then function

sqrt<double>

Remember that the compiler chooses the most specialized template function.

+4
source

In this case, as you noticed, there are two possible ways of matching the signature with the template. The first pattern template<class T> T sqrt(T)can be matched. Having T, equal complex<double>, makes a function (specialized specialization) with a signature complex<double> sqrt(complex<double>).

The second pattern template<class T> complex<T> sqrt(complex<T>)can also be matched. In this case, setting Tto doubledoes specialization with the same signature as the specialization of the first template.

: , complex<T>. , T - : :

template<class T> T sqrt(T);
template<class U> complex<U> sqrt(complex<U>);

, , . complex<double> T U, .

+3

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


All Articles