一、类模板全特化与偏特化
// 主模板
template <typename T>
struct TypeInfo {
static constexpr const char* name = "unknown";
};
// 全特化:T = int
template <>
struct TypeInfo<int> {
static constexpr const char* name = "int";
};
// 偏特化:T*(对所有指针类型)
template <typename T>
struct TypeInfo<T*> {
static constexpr const char* name = "pointer";
};
// 偏特化:const T(对所有 const 类型)
template <typename T>
struct TypeInfo<const T> {
static constexpr const char* name = "const";
};
// 使用
TypeInfo<double>::name; // "unknown"(主模板)
TypeInfo<int>::name; // "int"(全特化)
TypeInfo<float*>::name; // "pointer"(偏特化)
TypeInfo<const int>::name; // "const"(偏特化)
面试题:“为什么高性能库经常针对特定类型做全特化?”
- 因为通用实现(如逐元素循环)对 CPU 不友好,全特化可以换用 SIMD 指令(如
_mm256_loadu_si256)一次处理 8 个 int,速度提升 8 倍。
二、函数模板只能全特化,不能偏特化
template <typename T>
void func(T x) {}
template <> // ✅ 函数全特化
void func<int>(int x) {}
template <typename T>
void func<T*>(T* x) {} // ❌ 函数不能偏特化!编译错误
替代方案:用函数重载 + std::enable_if 或 if constexpr 实现类似效果。