目录
模板特化(Specialization)与偏特化(Partial Specialization)
模板模板参数(Template Template Parameters)
摘要
C++中的模板(template)是一种非常强大的工具,用于泛型编程和代码复用。模板可以分为函数模板、类模板、别名模板、变量模板、模板模板参数等。这些模板能够处理任意类型的数据,提高代码的灵活性和可重用性。
函数模板
函数模板允许函数对任意类型的数据进行操作。
基本用法
#include <iostream>
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
std::cout << "Max of 3 and 7: " << max(3, 7) << std::endl;
std::cout << "Max of 3.5 and 2.1: " << max(3.5, 2.1) << std::endl;
std::cout << "Max of 'a' and 'z': " << max('a', 'z') << std::endl;
return 0;
}
重载与特化
函数模板可以与普通函数重载,并且可以进行模板特化。
#include <iostream>
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
// 特化版本
template <>
const char* max(const char* a, const char* b) {
return (std::strcmp(a, b) > 0) ? a : b;
}
// 重载版本
int max(int a, int b) {
return (a > b) ? a : b;
}
int main() {
std::cout << "Max of 3 and 7: " << max(3, 7) << std::endl;
std::cout << "Max of \"hello\" and \"world\": " << max("hello", "world") << std::endl;
return 0;
}
// Out
Max of 3 and 7: 7
Max of "hello" and "world": world
类模板
类模板允许类处理任意类型的数据。
基本用法
#include <iostream>
template <typename T>
class Pair {
private:
T first, second;
public:
Pair(T a, T b) : first(a), second(b) {}
T getFirst() const { return first; }