在 C 中,为 int 动态数组写好的逻辑不能直接用于 double 或自定义对象,通常要依赖 void *、元素大小和回调函数。C++ 模板把类型作为参数,让编译器为具体类型生成类型安全的代码。
函数模板
#include <iostream>
#include <string>
template <typename T>
T maximum(const T& a, const T& b) {
return a < b ? b : a;
}
int main() {
std::cout << maximum(3, 7) << '\n';
std::cout << maximum(std::string("cat"), std::string("dog")) << '\n';
}
2026/7/17大约 3 分钟