22、模板特例化
C++的模板特化(Template Specialization)是指为特定类型或特定条件提供模板的特殊实现。模板特化分为两种:完全特化和部分特化。
- 完全特化(Full Specialization):为 “特定类型” 提供 “完全不同” 的实现。
- 部分特化(Partial Specialization):为 “某些类型” 或 “条件” 提供 “部分不同” 的实现。
完全特化示例
// 通用模板
template<typename T>
class MyClass {
public:void display() {std::cout << "Generic template" << std::endl;}
};// 完全特化, 对 int 类型的
template<>
class MyClass<int> {
public:void display() {std::cout << "Specialized template for int" << std::endl;}
};int main() {MyClass<double> obj1;obj1.display(); // 输出: Generic templateMyClass<int> obj2;obj2.display(); // 输出: Specialized template for intreturn 0;
}
部分特化示例
// 通用模板
template<typename T, typename U>
class MyClass {
public:void display() {std::cout << "Generic template" << std::endl;}
};// 部分特化
template<typename T>
class MyClass<T, int> {
public:void display() {std::cout << "Partially specialized template for second type int" << std::endl;}
};int main() {MyClass<double, double> obj1;obj1.display(); // 输出: Generic templateMyClass<double, int> obj2;obj2.display(); // 输出: Partially specialized template for second type intreturn 0;
}