C++ 模板是一种强大的编程技术,它允许你在编译时进行类型参数化,从而创建可重用的代码。通过使用模板,你可以编写一次代码,然后将其用于多种数据类型。
基本概念
模板函数
模板函数是C++模板的一种形式,它允许你定义一个函数,该函数可以接受任何类型的数据。
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
模板类
模板类是C++模板的另一种形式,它允许你定义一个类,该类可以接受任何类型的数据。
template <typename T>
class Stack {
private:
T* elements;
int top;
int capacity;
public:
Stack(int capacity) {
this->capacity = capacity;
elements = new T[capacity];
top = -1;
}
// ... 其他成员函数 ...
};
实用技巧
使用
typename
关键字当模板参数出现在
class
或struct
关键字之后时,你需要使用typename
关键字来区分。template<typename T> class MyClass { // ... };
使用
class
关键字当模板参数出现在
template
关键字之后时,你可以使用class
关键字。template<class T> class MyClass { // ... };
模板特化
你可以使用模板特化来为特定类型提供特定的实现。
template<typename T> T add(T a, T b) { return a + b; } template<> int add<int>(int a, int b) { return a + b + 1; // 特化实现 }
扩展阅读
想要深入了解C++模板编程?请阅读我们的《C++模板编程进阶》。
C++ Template