一个函数模板即有特化版又有重载版,编译器会选哪个?
以下代码来自:
为什么不要特化函数模版
的例3
 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 template<class T>
 6 void f(T)
 7 {
 8     cout << "Base template.\n";
 9 }
10 
11 template<>
12 void f(int*)
13 {
14     cout << "Explicit specialization.\n";
15 }
16 
17 template<class T>
18 void f(T*)
19 {
20     cout << "Overload of base template.\n";
21 }
22 
23 int main()
24 {
25     int * p;
26     f(p);
27 
28     return 0;
29 }
30 
代码中的f(int*)调用有两个选择,一是特化版,另一个是重载版。
结果是编译器选了重载版:Overload of base template.
(与我的期望相反,我并不想让指针版为int*实例化,所以辛辛苦苦为int*作了特化,结果编译器没理我!)
原因是:编译器是从所有的重载函数中选择,而特化不是一个重载。
这时仅有两个重载。当选中一个重载函数模板后,再在该模板的特化版本中选择。