Normal Conversions Apply for Nontemplate Arguments是錯誤還是疑問?

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的型別,到底是書錯了?還是我有疑問?

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *