#include<iostream>
#include<string>
using namespace std;
//类模板对象做函数参数
template<class T1, class T2 >
class person {
public:
T1 m_name;
T2 m_age;
person(T1 name, T2 age) {
m_name = name;
m_age = age;
}
void showperson() {
cout << "姓名:" << m_name << " 年龄: " << m_age << endl;
}
};
//1指定传入类型
void showperson1(person<string, int>&p)
{
p.showperson();
}
void test1() {
person<string, int> p1("孙悟空", 100);
showperson1(p1);
}
//2参数模板化
template<class T1,class T2>
void showperson2(person<T1,T2>& p) {
p.showperson();
cout << "T1的类型为: " << typeid(T1).name() << endl;
cout << "T2的类型为: " << typeid(T2).name() << endl;
}
void test2() {
person<string, int> p2("猪八戒", 90);
showperson2(p2);
}
//整个类模板化
template<class T>
void showperson3(T& p) {
p.showperson();
cout << "T的类型为: " << typeid(T).name() << endl;
}
void test3() {
person<string, int> p3("唐僧", 30);
showperson2(p3);
}
int main() {
test1();
test2();
test3();
system("pause");
return 0;
}
|