3

以下是“c++ 编程语言”中的几行

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>)
}

我不明白为什么 sqrt(z) ;电话sqrt<double>(complex<double>)可以任何机构请解释。

作者说, T sqrt<complex<T>> 比更专业,T sqrt <T>但有一个单独的声明template<class T > complex<T> sqrt(complex<T>);为什么不使用它?

4

2 回答 2

6

事后看来,如果 Bjarne 将其写为

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>)
}

so you don't get confused by all the different T's. But the idea is simple; C++ finds the best match. There are three possible functions. The first two are perfect matches (no conversion needed) so the non-template version is ignored. Now, we have T=complex and U=double. Which version is chosen? Bjarne explains the second template is chosen here, because it's more specialized. This means that for any type U, there is a type T=complex<U> which makes the signatures of both templates identical.

于 2008-10-20T09:55:58.527 回答
2

好吧,使用的函数就是您正在谈论sqrt<double>(complex<double>)的那个模板的实例template <class T> complex<T> sqrt(complex<T>)

您的误解在于模板实例的含义,而不是重载过程。

于 2008-10-20T09:47:13.863 回答