简单的案例
#include <iostream>#include <string>using namespace std;template<class NameType,class AgeType>class People{ public: string name; int age; People(NameType name,AgeType age){ this->name = name; this->age = age; } void show(){ cout << "姓名:" + name << ",年龄:" << age << endl; }};int main(){ People<string,int> p("小明",12);//类模板在调用时必须声明类型 p.show(); return 0;}
类模板和函数模板的区别
- 类模板不支持类型推导,估计在调用时必须声明类型(除非设置了默认参数)
- 类模板在模板参数表中可以有默认参数
设置类模板的默认数据类型
#include <iostream>#include <string>using namespace std;template<class NameType = string,class AgeType = int>//设置默认类型class People{ public: string name; int age; People(NameType name,AgeType age){ this->name = name; this->age = age; } void show(){ cout << "姓名:" + name << ",年龄:" << age << endl; }};int main(){ People<> p("小明",12);//在设置默认类型的情况下可以不声明,但<>还是要保留 p.show(); return 0;}