C++编程点滴3:函数模板重载问题

本文探讨了在C++中如何正确地实现和使用通用的max模板函数来比较不同类型的数据,包括基本类型、指针及字符串等,并展示了如何解决特定编译器(如VC6.0)下的编译错误。

#include<iostream>
#include<string>
#include<cstring>
template<typename T>
inline T const& max(T const& a,T const& b)
{
return a<b ? b:a;
}

template<typename T>
inline T * const& max(T *const& a,T* const& b)
{
return *a<*b?*b:*a;
}

template<typename T>
inline char const* const& max(char const* const& a,char const* const& b)
{
return std::strcmp(a,b)<0? b: a;
}


int main()
{
int a=6;
int b=38;
::max(a,b);

std::string s="hello";
std::string f="world";
::max(s,f);

int *p1=&b;
int *p2=&a;
::max(p1,p2); //这里报错

char const *s1 ="David";
char const *s2="Nico";
::max(s1,s2); //这里报错

return 0;
}

注意:在vc6.0重编译出错。

改成如下:

#include<iostream>
#include<string>
#include<cstring>

template<typename T>
inline T const& max(T const& a,T const& b)
{
return a<b ? b:a;
}

template<typename T>
inline T /***/ const& max(T *const& a,T* const& b)
{
return *a<*b?*b:*a;
}
#if 0
//template<typename T>
inline char const* const/*&*/ max(char const* const& a,char const* const& b)
{
return std::strcmp(a,b)<0? b: a;
}
#endif

int main()
{
int a=6;
int b=38;
::max(a,b);

std::string s="hello";
std::string f="world";
::max(s,f);

int *p1=&b;
int *p2=&a;
::max<int>(p1,p2); //这里报错

char const *s1 ="David";
char const *s2="Nico";
::max<const char>(s1,s2); //这里报错

return 0;
}


注意:max会被认为是重定义。需要指定具体使用的模板。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值