[英]c++ template function overloading
Below are lines from "the c++ programming language" 下面是“ 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>)
}
I dont understand why sqrt(z) ; 我不明白为什么sqrt(z); calls sqrt<double>(complex<double>)
can any body please explain. 调用sqrt<double>(complex<double>)
可以解释任何主体。
Author says, T sqrt<complex<T>>
is more specialized than T sqrt <T>
but there is a seperate declaration for template<class T > complex<T> sqrt(complex<T>);
作者说, T sqrt<complex<T>>
比T sqrt <T>
更专业,但是template<class T > complex<T> sqrt(complex<T>);
有一个单独的声明template<class T > complex<T> sqrt(complex<T>);
why not use that? 为什么不使用它?
In hindsight, it would have been easier if Bjarne would have written it as 事后看来,如果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. 这样您就不会对所有不同的T感到困惑。 But the idea is simple; 但是这个想法很简单。 C++ finds the best match. C ++找到最佳匹配。 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. 现在,我们有T = complex和U = double。 Which version is chosen? 选择哪个版本? Bjarne explains the second template is chosen here, because it's more specialized. Bjarne解释说这里选择了第二个模板,因为它更加专业。 This means that for any type U, there is a type T=complex<U>
which makes the signatures of both templates identical. 这意味着对于任何类型U,都有一个类型T=complex<U>
使两个模板的签名相同。
Well, the function used is the one you are talking about sqrt<double>(complex<double>)
is an instance of the template template <class T> complex<T> sqrt(complex<T>)
. 好吧,所使用的函数是您正在谈论的函数sqrt<double>(complex<double>)
是模板template <class T> complex<T> sqrt(complex<T>)
的实例。
Your misunderstanding was in the signification of the template instance and not in the overloading process. 您的误解是模板实例的含义,而不是重载过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.