15. 模板(Templates)
- Reuse source code
- generic programming
- use types as parameters in class or function definitions
- Template functions
- Template classes
15.1 Function Templates
- Perform similar operations on different types of data
- 示例:
// Swap function for two int arguments
void swap(int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
// swap function template
template <class T>
void swap(T& x, T& y) {
T temp = x;
x = y;
y = temp;
}
// The template keyword introduces the template
// The class T specifies a parameterized type name
// class means any built-in type or user-defined type
// Inside the template, use T as a type name
15.2 Class templates
- Classes parameterized by types
- Abstract operations from the types being operated upon
- Define potentially infinite set of classes
- Another step towards reuse
- Typical use: container classes
stack <int>
list <Person&>
queue <Job>
- 示例:
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;
};
// Vector 成员
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 {
...
}
}
// 使用:
int main() {
Vector<int> v1(100);
Vector<Complex> v2(256);
v1[20] = 10;
v2[20] = v1[20]; // ok, if int => Complex defined
}
15.3 Templates and inheritance
- 示例:
// Templates can inherit from non-template classes
template <class A>
class Derived : public Base { ... }
// Templates can inherit from template classes
template <class A>
class Derived : public List<A> { ... }
// Non-template classes can inherit from templates
class SupervisorGroup : public List<Employee*> { ... }
参考资料: