在C++中,模板不仅是STL的基础,也是现代泛型编程和元编程的核心机制。它通过编译期类型推导和代码生成,让同一份逻辑适配不同数据类型,同时避免运行时开销。下面从几个高级特性看它为何被称为神器。

模板参数推导与隐式实例化
函数模板可以根据实参自动推导类型,减少冗余声明。例如下面的交换函数:
#include <iostream>
template <typename T>
void swap_val(T& a, T& b) {
T tmp = a;
a = b;
b = tmp;
}
int main() {
int x = 1, y = 2;
swap_val(x, y); // 编译器推导 T 为 int
std::cout << x << " " << y << std::endl;
return 0;
}
特化与偏特化
当某些类型需要特殊逻辑时,可使用全特化或偏特化。下面展示一个类型特性判断的偏特化示例:
#include <iostream>
// 主模板:默认不是指针
template <typename T>
struct is_pointer { static const bool value = false; };
// 偏特化:指针类型
template <typename T>
struct is_pointer<T*> { static const bool value = true; };
int main() {
std::cout << is_pointer<int>::value << std::endl; // 0
std::cout << is_pointer<int*>::value << std::endl; // 1
return 0;
}
可变参数模板
C++11引入的可变参数模板支持任意数量参数,常用于泛型转发和元组实现:
#include <iostream>
// 递归终止函数
void print() {}
template <typename First, typename... Rest>
void print(First first, Rest... rest) {
std::cout << first << " ";
print(rest...);
}
int main() {
print(1, 2.5, "hello"); // 输出:1 2.5 hello
return 0;
}
模板元编程
模板可在编译期执行计算,例如编译期斐波那契数列:
#include <iostream>
template <int N>
struct fib {
static const int value = fib<N-1>::value + fib<N-2>::value;
};
template <>
struct fib<0> { static const int value = 0; };
template <>
struct fib<1> { static const int value = 1; };
int main() {
std::cout << fib<10>::value << std::endl; // 编译期算出55
return 0;
}
总结
从类型推导到编译期计算,C++模板提供了零成本抽象与极强复用能力。掌握这些高级特性,才能充分发挥泛型编程的威力,构建高效且通用的C++库。