您的位置:首页 > 编程语言 > C语言/C++

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

2009-03-08 13:30 197 查看
#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会被认为是重定义。需要指定具体使用的模板。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: