急需人才~~解下这个C++题目~~急需急需~谢谢了啊~

来源:百度知道 编辑:UC知道 时间:2024/06/15 09:49:09
设计一个函数模板,能够从int、char、float、double、long、char*等类型的数组找出最大值元素。提示:可用类型参数传递数组、用非类型参数传递数组大小,为了找出char*类型数组中的最大值元素,需要对该类型进行重载或特化

template<typename T,int len> T GetMax(const T& vec[])
{
T ret = vec[0];
for (int i=0; i<len; ++i)
{
if (ret<vec[i])
ret = vec[i];
}
return ret;
}
但是函数无法偏特化,所以对于char*类型上面函数无法偏特化,但用重载的话,又无法把数组的维数传进去。
因此最好引入类或结构进行特化处理(仿函数)
见下面实现:

// testtem.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <functional>
using namespace std;

template<>
struct greater<const char*>
: public binary_function<const char*,const char*, bool>
{
bool operator()(const char* & _Left, const char* & _Right) const
{ // apply operator< to operands
return strcmp(_Left,_Right)>=0 ? true : false;
}
};

template<typename T,int len> T GetMax( T vec[])
{
T* pret = &(vec[0]);
for (int i=0; i<len; ++i)
{
if (!greater&