模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的方式编写代码。模板是创建泛型类或函数的蓝图或公式。库容器,比如迭代器和算法,都是泛型编程的例子,它们都使用了模板的概念。下面是具体的使用:
#include <iostream>
using namespace std;
//p 历史版本
void MySwap(int &m_x, int &m_y)
{
int temp = m_x;
m_x = m_y;
m_y = temp;
}
//p 模板方式
//模板使用的第一种方法
template <class T>
void MySwap(T &m_x, T &m_y)
{
T temp = m_x;
m_x = m_y;
m_y = temp;
}
/* class 关键字表明T是一个类型,后来为了避免 class 在这两个地方的使用可能给人带来混淆,
所以引入了 typename 这个关键字,它的作用同 class 一样表明后面的符号为一个类型,这样
在定义模板的时候就可以使用下面的方式了: */
// template <typename T>
// void MySwap(T &m_x, T &m_y)
// {
// T temp = m_x;
// m_x = m_y;
// m_y = temp;
// }
//类模板的示例:这里使用了两个可变变量也使用了两种定义方式
template <typename T1, class T2>
class TextClass
{
public:
TextClass(T1 name, T2 age)
{
this->m_Age = age;
this->m_Name = name;
}
void Show()
{
cout << this->m_Name << "的年龄" << this->m_Age << endl;
}
private:
T1 m_Name;
T2 m_Age;
};
int main(int argc, char **argv)
{
int x = 10;
int y = 20;
cout << "x = " << x << " y = " << y << endl;
MySwap(x, y);
cout << "x = " << x << " y = " << y << endl;
string str_x = "hello ";
string str_y = "world ";
cout << str_y << str_x << endl;
MySwap<string>(str_x, str_y); //指定类型
// MySwap(str_x, str_y); //模板自动推导变量类型
cout << str_y << str_x << endl;
TextClass<string, int> Tc("张三", 20);
Tc.Show();
return 0;
}
单独拆分(类模板):
template <typename T1, class T2>
class TextClass
{
public:
TextClass(T1 name, T2 age)
{
this->m_Age = age;
this->m_Name = name;
}
void Show()
{
cout << this->m_Name << "的年龄" << this->m_Age << endl;
}
private:
T1 m_Name;
T2 m_Age;
};
类函数:
template <class T>
void MySwap(T &m_x, T &m_y)
{
T temp = m_x;
m_x = m_y;
m_y = temp;
}
class 关键字表明T是一个类型,后来为了避免 class 在这两个地方的使用可能给人带来混淆,所以引入了 typename 这个关键字,它的作用同 class 一样表明后面的符号为一个类型。
最后输出: