示例:求最大项
#include<iostream>
using namespace std;
template <class T>
void Max(T a,T b)
{
if(a>b)
cout<<a<<" is greater"<<endl;
else
cout<<b<<" is greater"<<endl;
}
int main() {
string a="abc";
string b="xyz";
Max(a, b);
Max<double>(1.1, 2.1);
}
传递参数
必须显式调用,参数可以缺省
#include<iostream>
using namespace std;
T* newmemomry() {
T *p = new T[size];
cout << "memory has been malloc" << endl;
return p;
}
void testnewmemomry() {
int *p = newmemomry<int, 10>();
double *q = newmemomry<double, 10>();
char *r = newmemomry<char, 10>();
}
int main() {
testprint();
}
函数模板重载
先匹配普通函数
再寻求函数模板
#include<iostream>
using namespace std;
template<class T>
void print(T a)
{
cout << "函数模板..." << endl;
cout<<a<<endl;
}
void print(int a)
{
cout << "普通函数..." << endl;
cout<<a<<endl;
}
void testprint() {
print(1);
print(1.1);
print<int>(1);
print("hello");
}
int main() {
testprint();
}