template 怎么用
时间: 2024-01-27 17:03:10 浏览: 69
template 是一种在编程中常用的技术,用于创建可重用的代码模板。它可以帮助我们更高效地开发和维护代码。在不同的编程语言中,template 的具体使用方式可能会有所不同。
在 C++ 中,template 是一种泛型编程的机制,可以实现类型参数化。通过使用 template,我们可以编写一些通用的代码,可以在不同的数据类型上进行操作。
下面是一个简单的示例,展示了如何在 C++ 中使用 template:
```cpp
#include <iostream>
// 定义一个模板函数
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
int num1 = 5, num2 = 10;
double double1 = 3.14, double2 = 2.718;
// 调用模板函数并输出结果
std::cout << "Max of " << num1 << " and " << num2 << " is: " << max(num1, num2) << std::endl;
std::cout << "Max of " << double1 << " and " << double2 << " is: " << max(double1, double2) << std::endl;
return 0;
}
```
上述代码中,我们定义了一个模板函数 `max`,它接受两个类型为 `T` 的参数,并返回较大的那个值。在 `main` 函数中,我们分别传入了两个整数和两个浮点数作为参数,并调用了 `max` 函数来比较它们的大小。
阅读全文
相关推荐













