C++ Primer 4/e在Normal Conversions Apply for Nontemplate Arguments这个地方有这段的程式码及叙述:‘Normal conversions (Section 7.1.2, p. 229) are allowed for parameters defined using ordinary types. The following function template sum has two parameters:
template <class Type> Type sum(const Type &op1, int op2) { return op1 + op2; }
The first parameter, op1, has a template parameter type. Its actual type cannot be known until the function is used. The type of the second parameter, op2, is known: It’s int.
Because the type of op2 is fixed, normal conversions can be applied to arguments passed to op2 when sum is called:
double d = 3.14; string s1("hiya"), s2(" world"); sum(1024, d); // ok: instantiates sum(int, int), converts d to int sum(1.4, d); // ok: instantiates sum(double, int), converts d to int sum(s1, s2); // error: s2 cannot be converted to int
In the first two calls, the type of the second argument dd is not the same as the type of the corresponding function parameter. However, these calls are okay: There is a conversion from double to int. Because the type of the second parameter does not depend on a template parameter, the compiler will implicitly convert dd. The first call causes the function sum(int, int) to be instantiated; sum(double, int) is instantiated by the second call.’
中文版的这样写:‘“以一般型别定义的参数”仍可施行一般转换(7.1.2节,p.229)。以下的function template sum有两个参数:
template <class Type> Type sum(const Type &op1, int op2) { return op1 + op2; }
第一参数op1的型别是template参数,其实际型别在函式被使用之前无法得知。第二参数op2的型别已知,是个int。
由于op2的型别固定,所以sum()被呼叫时,可在“传给op2的引数”身上施行一般转换:
double d = 3.14; string s1("hiya"), s2(" world"); sum(1024, d); // 没问题:具现出sum(int,int),将d转换为int sum(1.4, d); // 没问题:具现出sum(double,int),将d转换为int sum(s1, s2); // 错误:s2无法转换为int
在前两个呼叫式中,第二引数dd的型别不同于其所对应的参数型别。然而这两个呼叫都没有问题,因为double和int之间存在转换关系。由于第二参数的型别不相依于某个template参数,所以编译器会暗自转换dd。第一个呼叫式会具现出sum(int,int);第二个呼叫式会具现出sum(double,int)。’
dd?我看到程式码中都是叫d的型别哪有dd的型别,到底是书错了?还是我有疑问?