C++泛型编程:类模板(上)
类模板与函数模板的区别:
类模板没有自动类型推导的使用方式
类模板在模板参数列表中可以有默认参数
template <class NameType,class AgeType = int>
class Person
{
public:
Person(NameType name, AgeType age);
void showPerson()
{
cout << this->m_Name << " " << this->m_Age << endl;
}
NameType m_Name;
AgeType m_Age;
};
template <class NameType, class AgeType>
Person<NameType,AgeType>::Person(NameType name, AgeType age)
{//类模板中成员函数类外实现需要加上模板参数列表
this->m_Name = name;
this->m_Age = age;
}
void test01()
{
Person<string, int>p1("孙悟空",999);
p1.showPerson();
Person<string>p2("ZN", 19);
p2.showPerson();
}
类模板中成员函数创建时机:
类模板中成员函数在调用时才创建
class Class1
{
public:
void show1()
{
cout << "Person1" << endl;
}
};
class Class2
{
public:
void show2()
{
cout << "Person2" << endl;
}
};
template <class T>
class Myclass
{
public:
T obj;
void func1() { obj.show1(); }
void func2() { obj.show2(); }
};
void test02()
{
Myclass<Class1> p1;
p1.func1();
}
类模板对象做函数参数:
①指定传入类型(最常用)
void printPerson1(Person<string, int>& p)
{
p.showPerson();
}
②参数模板化
template <typename T1,typename T2>
void printPerson2(Person<T1,T2>& p)
{
p.showPerson();
cout << "T1的类型为:" << typeid(T1).name() << endl;
cout << "T2的类型为:" << typeid(T2).name() << endl;
}
③整个类模板化
template <typename T>
void printPerson3(T &p)
{
p.showPerson();
cout << "T的数据类型:" << typeid(T).name() << endl;
}
void test03()
{
Person<string, int> p1("Ning", 19);
printPerson1(p1);
printPerson2(p1);
printPerson3(p1);
}
运行结果:
Ning 19
Ning 19
T1的类型为:class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
T2的类型为:int
Ning 19
T的数据类型:class Person<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int>