.设计两个函数模板,其功能分别是返回两个值中的较大者和返回多个值中的较大者。要求不仅能够处理整型、实型等数值型数据,而且能够正确处理字符串。
时间: 2024-03-23 12:37:50 浏览: 22
下面是两个函数模板的实现:
```c++
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T max(T a, T b) {
return a > b ? a : b;
}
template <typename T>
T max(T a, T b, T c) {
return max(max(a,b), c);
}
template <typename T>
T max(T a, T b, T c, T d) {
return max(max(a,b), max(c,d));
}
int main() {
int i1 = 1, i2 = 2;
cout << max(i1, i2) << endl; // 输出 2
double d1 = 1.1, d2 = 2.2;
cout << max(d1, d2) << endl; // 输出 2.2
string s1 = "hello", s2 = "world";
cout << max(s1, s2) << endl; // 输出 world
cout << max(1, 2, 3) << endl; // 输出 3
cout << max(1, 2, 3, 4) << endl; // 输出 4
return 0;
}
```
这里实现了两个函数模板,第一个模板 `max` 用于返回两个值中的较大者,第二个模板 `max` 用于返回多个值中的较大者。通过重载函数模板,我们可以支持不同数量的参数。这两个函数模板都能处理整型、实型等数值型数据,以及字符串类型的数据,因为这些类型都支持比较操作符 `>`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)