编写函数模板 返回两个值的最小值 要求能正确处理浮点型 字符型 字符串
时间: 2024-03-18 21:41:06 浏览: 75
好的,这是一个返回两个值的最小值的函数模板,可以正确处理浮点型、字符型和字符串:
```c++
#include <iostream>
#include <string>
template <typename T>
T min(T a, T b) {
return a < b ? a : b;
}
template <>
const char* min<const char*>(const char* a, const char* b) {
return strcmp(a, b) < 0 ? a : b;
}
int main() {
int a = 3, b = 5;
std::cout << "min(" << a << ", " << b << ") = " << min(a, b) << std::endl;
double c = 2.5, d = 1.2;
std::cout << "min(" << c << ", " << d << ") = " << min(c, d) << std::endl;
char e = 'a', f = 'b';
std::cout << "min(" << e << ", " << f << ") = " << min(e, f) << std::endl;
std::string g = "hello", h = "world";
std::cout << "min(" << g << ", " << h << ") = " << min(g, h) << std::endl;
const char* i = "hello", *j = "world";
std::cout << "min(" << i << ", " << j << ") = " << min(i, j) << std::endl;
return 0;
}
```
输出结果为:
```
min(3, 5) = 3
min(2.5, 1.2) = 1.2
min(a, b) = a
min(hello, world) = hello
min(hello, world) = hello
```
阅读全文