普通函数和函数模板调用规则
调用规则
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;
}

从这些结果就知道了

浙公网安备 33010602011771号