1

在以下幾點:默認vs推測模板參數?

template<typename Type> 
struct MyClass 
{ 
    template<typename OtherType> MyClass(const MyClass<OtherType>& x); 
    template<typename OtherType = Type> void test(const MyClass<OtherType>& x); 
}; 

在功能test所做的事情之間:

案例1:默認參數是優先級:轉換構造MyClass<Type>(const MyClass<OtherType>& x)被隱含調用,MyClass<Type>::test<Type>(const MyClass<Type>& x)是調用。

案例2:推導出的參數優先:調用MyClass<Type>::test<Type>(const MyClass<OtherType>& x)


我認爲很好的答案是第二個,但我不確定。你能證實我的看法嗎(並且這種情況是由標準定義的)?


編輯:測試函數的調用:

MyClass<double> d; 
MyClass<unsigned int> ui; 
d.test(ui); // <- So the question is : is ui implicitely 
      // converted to MyClass<double> or not ? 

回答

2
test

將被稱爲

MyClass<double>::test(const MyClass<unsigned int> &) 

即不會有任何的ui轉換從MyClass<unsigned int>MyClass<double>

默認模板參數不會覆蓋給定的模板參數。只有在沒有給出模板參數並且編譯器不能從函數參數中推導出它時纔會使用它。

從C++ 11標準:

(§14.8.2/ 5)將得到的取代的和調節功能類型被用作模板參數推導函數模板的類型。如果沒有推導出模板參數,則使用其默認模板參數(如果有的話)。 [實施例:

template <class T, class U = double> 
void f(T t = 0, U u = 0); 
void g() { 
    f(1, ’c’);  // f<int,char>(1,’c’) 
    f(1);   // f<int,double>(1,0) 
    f();   // error: T cannot be deduced 
    f<int>();  // f<int,double>(0,0) 
    f<int,char>(); // f<int,char>(0,0) 
} 

- 端示例]