`
BlogDown
  • 浏览: 213334 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多

#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会被认为是重定义。需要指定具体使用的模板。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics