函式範本可以多載同名的非樣板函式。 在此案例中,編譯程式會先嘗試使用樣板自變數推斷解析函式呼叫,以具現化具有唯一特製化的函式範本。 如果樣板自變數推算失敗,則編譯程式會考慮具現化函式範本多載和非樣板函式多載來解析呼叫。 這些其他多載稱為 候選集。 如果樣板自變數推算成功,則產生的函式會與候選集合中的其他函式進行比較,以判斷最佳比對,並遵循多載解析的規則。 如需詳細資訊,請參閱 函式多載。
範例:選擇非範本函式
如果非樣板函式與函式範本同樣相符,則會選擇非範本函式(除非明確指定範本自變數),如下列範例中的呼叫 f(1, 1)
所示。
// template_name_resolution9.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
void f(int, int) { cout << "f(int, int)" << endl; }
void f(char, char) { cout << "f(char, char)" << endl; }
template <class T1, class T2>
void f(T1, T2)
{
cout << "void f(T1, T2)" << endl;
}
int main()
{
f(1, 1); // Equally good match; choose the non-template function.
f('a', 1); // Chooses the function template.
f<int, int>(2, 2); // Template arguments explicitly specified.
}
f(int, int)
void f(T1, T2)
void f(T1, T2)
範例:慣用完全相符函式範本
下一個範例說明如果非範本函式需要轉換,則偏好完全相符的函式範本。
// template_name_resolution10.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
void f(int, int) { cout << "f(int, int)" << endl; }
template <class T1, class T2>
void f(T1, T2)
{
cout << "void f(T1, T2)" << endl;
}
int main()
{
long l = 0;
int i = 0;
// Call the function template f(long, int) because f(int, int)
// would require a conversion from long to int.
f(l, i);
}
void f(T1, T2)