问题:
解答:
#include <iostream>
using namespace std;template <typename T>
T maxn(T arr[], int len)//通用
{T max = 0;for (int i = 0; i < len; i++){if (max < arr[i]){max = arr[i];}}return max;
}template<>
const char* maxn<const char*>(const char* c[], int len)
{const char* p = c[0];int size = strlen(p);for (int i = 1; i < len; i++){if (size < strlen(c[i])){p = c[i];}}return p;
}int main()
{int max = 0;double max1 = 0.0;int a1[6] = { 1,2,3,4,5,6 };double d1[4] = { 1.1,2.2,3.3,4.4 };max = maxn(a1, 6);max1 = maxn(d1, 4);cout << "int中最大的数为:" << max <<endl;cout << "double中最大的数为:" << max1 << endl;const char* p[5] = { "1","12","123","1234","12345" };const char* c= maxn(p, 5);cout << "字符数组中最长的字符为:" << c << endl;return 0;
}
运行结果:
考查点:
- 模版函数
- 模版函数具体化
注意:
- 模版函数具体化会被优先调用
- 可以自定义一些通用模版函数做不到的.
2024年9月1日21:54:55