模板是编译时多态, 函数体内是运行时,运行时判断类型是type_id函数返回type_info类型的对象
这里只需要个模板特化就可以了
template<typename T>
T work( T )
{
// 编译时,不可能知道T是什么类型.所以T叫做泛型.
}
template<> // 特化版
int work<int>( int a)
{
// 这里明确知道T是int.
// 在这里提供对 T == int时的特殊处理
}
也就是你要知道T是什么类型,你就必须提供静态版本的多态.
编译时不可能有什么函数来给你判断T是什么类型.
#include <iostream>
using namespace std;
template < typename T >
T maxValue (const T array[], const int size)
{
T t=array[0];
for(int i=0;i<size;i++)
{
if(array[i]>t)
t = array[i];
}
return t;
}
template <>
string maxValue<string> (const string array[], const int size)
{
int s=0;
int k=0;
for(int i=0;i<size;i++)
{
int s_=0;
int len=array[i].length();
for(int j=0;j<len;j++)
{
if(array[i][j]>='A' && array[i][j]<='Z')
s += (array[i][j]-'A');
else
s += (array[i][j]-'a');
}
if(s_>s)
k=i;
}
string r=array[k];
return r;
}
模版特例化
最新推荐文章于 2024-08-09 10:25:03 发布