模板的局限性
局限性:模板的通用性并不是万能的
例如判断两个数是否相等的模板,假如传入的是一个Person类,或者一个数组,就会出问题了。
因此C++为了解决这种问题,提供模板的重载,可以为这些特定的类型提供具体化的模板
#include<iostream>
using namespace std;
#include<string>
template<typename T>
bool myCompare(T& a, T& b)
{
return a == b;
}
void test()
{
int a = 20, b = 20;
bool ret = myCompare(a, b);
if (ret)
{
cout << "a==b" << endl;
}
else {
cout << "a!=b" << endl;
}
}
class Person {
public:
string name;
int age;
Person(string name, int age)
{
this->name = name;
this->age = age;
}
};
//利用具体化Person的版本实现代码,会优先调用这个。
template<> bool myCompare(Person& p1, Person& p2)
{
if (p1.name == p2.name && p1.age == p2.age)
{
return true;
}
else {
return false;
}
}
void test01()
{
Person p1("tom", 18);
Person p2("tom", 16);
bool ret = myCompare(p1, p2);
if (ret)
{
cout << "p1==p2" << endl;
}
else {
cout << "p1!=p2" << endl;
}
}
int main()
{
//test();
test01();
}总结:
- 利用具体化的模板,可以解决自定义类型的通用化
- 学习模板并不是为了写模板,而是在STL能够运用系统提供的模板
类模板的基本语法
类模板作用:建立一个通用类,类中的成员数据类型可以不具体制定,用一个虚拟的类型来代表。
语法:template <typename T>类
解释:
- template:声明创建模板
- typename:表面其后面的符号是一种数据类型,可以用class代替
- T通用的数据类型,名称可以替换,通常为大写字母
#include<iostream>
using namespace std;
#include<string>
template<class T1, class T2>
class Person
{
public:
Person(T1 name, T2 age)
{
this->name = name;
this->age = age;
}
T1 name;
T2 age;
void show()
{
cout << name << endl;
cout << age << endl;
}
};
void test()
{
Person<string, int> p1("张三", 20);
p1.show();
}
int main()
{
test();
}总结:类模板和函数模板语法相似,在声明模板template后面加类,此类称为类模板
类模板
类模板与函数模板区别主要有两点:
- 类模板没有自动类型推导的使用方式(c++17之后有了)
- 类模板在模板参数列表中可以有默认参数
#include<iostream>
using namespace std;
#include<string>
//模板也可以指定默认参数
template<class T1 = string, class T2 = int>
class Person
{
public:
T1 name;
T2 age;
Person(T1 name, T2 age)
{
this->name = name;
this->age = age;
}
void show()
{
cout << name << endl;
cout << age << endl;
}
};
void test1()
{
Person p1("張三", 18);
Person p2("李四", 20);
p1.show();
p2.show();
}
void test2()
{
Person p("tom", 20);
p.show();
}
int main()
{
//test1();
test2();
}总结:
- 类模板使用只能用显示指定类型方式(c++17之后有了自动类型推导,可以不指定了)
- 类模板中的模板参数列表可以有默认参数
类模板中成员函数的创建时机
类模板中成员函数和普通类中成员函数创建时机是有区别的:
- 普通类中的成员函数一开始就可以创建
类模板中的成员函数在调用时才创建
#include<iostream> using namespace std; #include<string> class Person1 { public: void showPerson1() { cout << "Person 1 show" << endl; } }; class Person2 { public: void showPerson2() { cout << "Person 2 show" << endl; } }; template<class T> class MyClass { public: T obj; void func1() { obj.showPerson1(); } void func2() { obj.showPerson2(); } }; void test01() { MyClass<Person1> m; m.func1(); //m.func2();报错,Perosn1不能调用Person2的showPerson2()。 } int main() { test01(); }总结:类模板中的成员函数并不是一开始就创建的,在调用时才去创建.因为使用了模板,我们无法确定obj的类型。