函数模板调用的重载解析

函数模板可以重载具有相同名称的非模板函数。 在此方案中,编译器首先尝试使用模板自变量推导来解析函数调用,以实例化具有唯一特化的函数模板。 如果模板自变量推导失败,则编译器会考虑实例化函数模板重载和非模板函数重载来解析调用。 这些其他重载称为候选集。 如果模板自变量推导成功,则按照重载决策的规则,将生成的函数与候选集中的其他函数进行比较,以确定最佳匹配。 有关详细信息,请参阅函数重载

示例:选择非模板函数

如果非模板函数是函数模板的很好的匹配,则选择非模板函数(除非已显式指定模板自变量),如以下示例中的 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)

另请参阅

名称解析
typename