調用規則
1.如果普通函數和模板函數都可調用,優先普通函數
2.可以通過空模版參數列表 強制調用 函數模板
3.函數模板可以發生函數重載
4.如果函數模板可以產生更好的匹配,優先調用函數模板
先對第一,二條驗證
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 void Print(int a,int b) 5 { 6 cout << "hello" << endl; 7 } 8 9 template<class T> 10 void Print(T a,T b) 11 { 12 cout << "world" << endl; 13 } 14 15 void test() 16 { 17 int a = 1,b = 2; 18 Print(a,b); 19 Print<>(a,b); 20 } 21 22 int main() 23 { 24 test(); 25 return 0; 26 }
第三條
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 void Print(int a,int b) 5 { 6 cout << "hello" << endl; 7 } 8 9 template<class T> 10 void Print(T a,T b) 11 { 12 cout << "world" << endl; 13 } 14 15 template<class T> 16 void Print(T a,T b,T c) 17 { 18 cout << "overload world" << endl; 19 } 20 21 void test() 22 { 23 int a = 1,b = 2; 24 Print(a,b,100); 25 //Print(a,b); 26 //Print<>(a,b); 27 } 28 29 int main() 30 { 31 test(); 32 return 0; 33 }
第四條
#include<bits/stdc++.h> using namespace std; void Print(int a,int b) { cout << "hello" << endl; } template<class T> void Print(T a,T b) { cout << "world" << endl; } template<class T> void Print(T a,T b,T c) { cout << "overload world" << endl; } void test() { int a = 1,b = 2; //Print(a,b,100); //Print(a,b); //Print<>(a,b); char c1 = 'a',c2 = 'b'; Print(c1,c2); } int main() { test(); return 0; }
從這些結果就知道了