如果您註釋掉引用的雙參數max
的定義,您會看到代碼無法編譯。是MSVC++ 2013提供了在22行的錯誤是:
error C2440: 'return' : cannot convert from 'const int *' to 'int *const &'
這似乎是爲什麼max
爲引用總是選擇理由:max
爲指針模板替換失敗。 如果你的代碼更改爲以下,則指針模板被稱爲:
#include <iostream>
using namespace std;
template <class T>
T max(const T& a1, const T& a2)
{
cout << "general template" << endl;
return (a1 < a2) ? a2 : a1;
}
template <class T>
T* max(T* a1, T* a2)
{
cout << "template for pointers" << endl;
return (a1 < a2) ? a2 : a1;
}
template <class T>
T max(const T& a1, const T& a2, const T& a3)
{
cout << "general template with three parameters" << endl;
return ::max(::max(a1, a2), a3);
}
int main()
{
int* a = new int(5);
int* b = new int(56);
int* c = new int(2);
int* g = ::max(a, b, c);
cout << *g << endl;
return 0;
}
如果您註釋掉模板指針的定義,然後引用模板被調用。由於類型已經是一個指針,因此模板的指針優先於模板的引用似乎發生。
這裏是模板匹配的訂單上的解釋:What are the rules for choosing from overloaded template functions?
編輯:OP的代碼可以以另一種方式被改變,從而使MSVC++ 2013更喜歡基於參考的模板,基於指針:
#include <iostream>
using namespace std;
template <class T>
T max(const T& a1, const T& a2)
{
cout << "general template" << endl;
return (a1 < a2) ? a2 : a1;
}
template <class T>
const T* max(const T* a1, const T* a2)
{
cout << "template for pointers" << endl;
return (a1 < a2) ? a2 : a1;
}
template <class T>
T max(const T& a1, const T& a2, const T& a3)
{
cout << "general template with three parameters" << endl;
return const_cast<const T>(::max(::max(a1, a2), a3));
}
int main()
{
int* a = new int(5);
int* b = new int(56);
int* c = new int(2);
int* g = ::max(a, b, c);
cout << *g << endl;
return 0;
}
發生這種情況是因爲在此版本中,基於指針的模板定義具有其參數類型的其他限定符:它們不僅僅是T*
,而是const T*
。
我會避免'使用命名空間標準;',甚至更多當你聲明具有衝突名稱的函數('std :: max'存在)。 – Jarod42
感謝您的諮詢。我只是在測試模板功能。 – user1289