C++模板机制:函数模板与类模板的实践应用
在C++中,模板是实现泛型编程的核心机制,它允许开发者编写与类型无关的通用代码。相较于函数重载,模板通过编译时类型推导避免了为每种数据类型重复定义逻辑相同但签名不同的函数,显著提升了代码复用性与可维护性。
函数模板:统一接口,多态实现
假设需要实现一个返回两参数中较小值的通用函数。若采用重载方式,需分别为 int、double、char 等类型单独编写函数;而使用函数模板,则只需一份定义:
// 通用最小值函数模板
template <typename ValueType>
ValueType select_smaller(ValueType a, ValueType b) {
return (a < b) ? a : b;
}
该模板声明中,typename ValueType 是类型形参(也可写作 class ValueType),编译器在调用时根据实参自动推导其具体类型。例如:
#include <iostream>
int main() {
int x = 42, y = 17;
double u = 3.14, v = 2.71;
std::cout << "Min int: " << select_smaller(x, y) << "\n";
std::cout << "Min double: " << select_smaller(u, v) << "\n";
char p = 'm', q = 'z';
std::cout << "Min char: " << select_smaller(p, q) << "\n";
return 0;
}
上述三次调用分别实例化出 select_smaller<int>、select_smaller<double> 和 select_smaller<char> 三个具体函数,无需手动指定模板参数——类型推导由编译器完成。
类模板:参数化数据结构
类模板将类型抽象提升至整个类层级,适用于构建容器、智能指针等通用组件。以下是一个双类型参数的容器类示例:
// PairContainer.h
#ifndef PAIR_CONTAINER_H
#define PAIR_CONTAINER_H
#include <iostream>
template <typename FirstType, typename SecondType>
class PairContainer {
private:
FirstType first_value;
SecondType second_value;
public:
PairContainer(FirstType f, SecondType s)
: first_value(f), second_value(s) {}
void display() const {
std::cout << "First=" << first_value
<< ", Second=" << second_value << "\n";
}
};
#endif
使用时可灵活组合不同类型:
#include "PairContainer.h"
int main() {
PairContainer<int, std::string> pair1{42, "answer"};
pair1.display(); // 输出:First=42, Second=answer
PairContainer<double, bool> pair2{3.14159, true};
pair2.display(); // 输出:First=3.14159, Second=1
return 0;
}
非类型模板参数:编译期常量注入
除类型外,模板还可接受整型常量、枚举值或具有外部链接的指针作为参数,这类参数在编译期确定且不可修改。典型应用场景是固定大小缓冲区:
template <typename ElementType, std::size_t Capacity>
class FixedArray {
private:
ElementType data[Capacity];
std::size_t size_ = 0;
public:
void append(ElementType val) {
if (size_ < Capacity) {
data[size_++] = val;
}
}
ElementType at(std::size_t idx) const {
return (idx < size_) ? data[idx] : ElementType{};
}
};
实例化时直接传入尺寸字面量:
FixedArray<int, 8> small_buffer;
FixedArray<char, 256> large_buffer;
注意:浮点字面量、局部变量地址或字符串字面量(无外部链接)均不能作为非类型模板参数。