类模板实例化出的对象,向函数传参的方式
一共有三种传入方式:
- 指定传入的类型 — 直接显示对象的数据类型
- 参数模板化 — 将对象中的参数变为模板进行传递
- 整个类模板化 — 将这个对象类型 模板化进行传递
总结:比较广泛使用的是第一种,指定类型传入
#include<iostream>
using namespace std;
//类模板
template<class Nametype,class agetype = int>
class Person
{
public:
Person(Nametype name, agetype age)
{
this->mname = name;
this->mage = age;
}
Nametype mname;
agetype mage;
void showPerson()
{
cout << "name: " << mname << "age: " << mage << endl;
}
};
//1 指定传入的类型
void printPerson1(Person<string, int>& p)
{
p.showPerson();
}
void test01()
{
Person<string, int>p("黄刚", 21);
printPerson1(p);
}
//2.参数模板化
template<class T1,class T2>
void printPerson2(Person<T1, T2>& p)
{
p.showPerson();
cout << "T1的类型为: "<<typeid(T1).name() << endl;
//T1的类型为: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
cout << "T2的类型为: " << typeid(T2).name() << endl;
//T2的类型为: int
}
void test02()
{
Person<string, int>p("黄刚", 100);
printPerson2(p);
}
//3.整个类模板化
template<class T3>
void printPerson3(T3& p)
{
cout << "T3的类型为: "<<typeid(T3).name() << endl;
//T3的类型为: class Person<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int>
p.showPerson();
}
void test03()
{
Person<string, int>p("黄刚", 100);
printPerson3(p);
}
int main()
{
test01();
test02();
test03();
return 0;
}