C++类模板偏特化
C++类模板偏特化
类模板偏特化允许为模板参数的子集提供特殊实现。与函数模板只能完全特化不同,类模板支持偏特化,提供了更大的灵活性。
类模板的基本定义提供通用实现。
#include
#include
template
class Pair {
T first_;
U second_;
public:
Pair(const T& first, const U& second) : first_(first), second_(second) {}
void display() const {
std::cout << "Generic Pair: " << first_ << ", " << second_ << "\n";
}
};
void basic_template() {
Pair p1(10, 3.14);
p1.display();
}
偏特化为部分模板参数提供特殊实现。
template
class Pair {
T first_;
T second_;
public:
Pair(const T& first, const T& second) : first_(first), second_(second) {}
void display() const {
std::cout << "Same type Pair: " << first_ << ", " << second_ << "\n";
}
T sum() const {
return first_ + second_;
}
};
void partial_specialization() {
Pair p(10, 20);
p.display();
std::cout << "Sum: " << p.sum() << "\n";
}
指针类型的偏特化。
template
class Pair {
T* first_;
T* second_;
public:
Pair(T* first, T* second) : first_(first), second_(second) {}
void display() const {
std::cout << "Pointer Pair: " << *first_ << ", " << *second_ << "\n";
}
};
void pointer_specialization() {
int x = 10, y = 20;
Pair p(&x, &y);
p.display();
}
const类型的偏特化。
template
class Container {
T value_;
public:
explicit Container(const T& value) : value_(value) {}
void modify() {
value_ = T();
std::cout << "Modified\n";
}
};
template
class Container {
T value_;
public:
explicit Container(const T& value) : value_(value) {}
void modify() {
std::cout << "Cannot modify const container\n";
}
};
数组类型的偏特化。
template
class Array {
T data_[N];
public:
T& operator[](size_t index) { return data_[index]; }
size_t size() const { return N; }
};
template
class Array {
public:
size_t size() const { return 0; }
};
类型特征使用偏特化实现。
template
struct IsPointer {
static constexpr bool value = false;
};
template
struct IsPointer {
static constexpr bool value = true;
};
template
struct RemovePointer {
using type = T;
};
template
struct RemovePointer {
using type = T;
};
void type_traits_example() {
std::cout << "int is pointer: " << IsPointer::value << "\n";
std::cout << "int* is pointer: " << IsPointer::value << "\n";
using Type = RemovePointer::type;
std::cout << "Type is int: " << std::is_same::value << "\n";
}
偏特化可以根据模板参数数量进行。
template
class Tuple;
template<>
class Tuple<> {
public:
void display() const {
std::cout << "Empty tuple\n";
}
};
template
class Tuple {
Head head_;
Tuple tail_;
public:
Tuple(const Head& head, const Tail&... tail)
: head_(head), tail_(tail...) {}
void display() const {
std::cout << head_ << " ";
tail_.display();
}
};
类模板偏特化是实现类型特征和元编程的重要工具。
