模板
为什么使用模板(Why templates?)
代码重用
- 泛型编程
- 将数据类型作为函数或类的参数
函数模板(Function Templates)
函数模板为可视为函数声明
template <class T>
void swap( T& x, T& y)
{
T temp = x;
x = y;
y = temp;
}
template 模板的关键字
将T作象征数据类型
使用函数模板
//相当于函数重载,编译器会重新制造不同的同名函数
int i = 3;
int j = 4;
swap(i , j)
float k = 4.5;
float m = 3,7;
sawp(k, m);
std::string s("Hello");
std::string t("World");
swap(s, t);
模板的作用是告诉编译器如何制造新的函数
正确使用swap()
swap(int, int); //ok
sawp(double, double);//ok
swap(int, double);//error!
使用函数模板时数据之间没有隐式转换
函数重载规则
- 编译器查找唯一的匹配函数
- 编译器查找唯一的匹配函数模板
- 编译器查找匹配的重载函数
类模板
template <class T>
class Vector
{
public:
Vector(int);
~Vector();
Vector(const Vector&);
Vector& operator=(const Vector&);
T& operator[] (int);
private:
T* m_elements;
int m_size;
};
类模板成员函数
每一个函数都是函数模板,都要加上
template <class T>
Vector<T>::Vector(int size) : m_size(size)
{
m_elements = new T[m_size];
}
template <class T>
T& Vector<T>::operator[] (int index)
{
if (index < m_size && index > 0)
{
return m_elements[index];
}
else
{
...
}
}
使用类模板
Vector<int> v1(100);
Vector<Complex> v2(256);
v1[20] = 10;
v2[20] = v1[20]; // ok if int->Complex
其他
多参数类模板
template <class Key, class Value>
class HashTable
{
const Value& lookup(const Key&) const;
void install(const Key&, const Value&);
...
};
Vector< vector< double *> >
Vector< int (*)vector< double>&, int>
template <class T, int bounds = 100>
class FixedVector
{
public:
FixedVector();
//...
T& operator[] (int);
private:
T elements[bounds];
};
usage
FixedVector<int, 50> v1;
FixedVector<int, 10*5> v2;
FixedVector<int> v3;
类模板的继承
1. Templates can inherit from non-template class
2. Templates can inherit from temlate class
3. Non-tempalte class can inherit from tempaltes
类模板的实现原理
两次编译
相当于先制造一个模子,在根据模子制造函数
.cpp文件----》 .i文件(无脑预编译)----》 .obj文件(汇编)----》.exe(链接形成)