首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++函数模板重载

C++函数模板重载
EN

Stack Overflow用户
提问于 2012-02-09 14:22:24
回答 1查看 975关注 0票数 1

这个例子来自Josuttis的C++ templates一书:

代码语言:javascript
复制
 #include <iostream>
 #include <cstring>
 #include <string>

 // maximum of two values of any type (call-by-reference)
 template <typename T>
 inline T const& max (T const& a, T const& b)
 {
     return  a < b  ?  b : a;
 }

 // maximum of two C-strings (call-by-value)
 inline char const* max (char const* a, char const* b)
 { 
    return  std::strcmp(a,b) < 0  ?  b : a;
 }

 // maximum of three values of any type (call-by-reference)
 template <typename T>
 inline T const& max (T const& a, T const& b, T const& c)
 {
     return max (max(a,b), c);  // error, if max(a,b) uses call-by-value
 }

 int main ()
 {
   ::max(7, 42, 68);     // OK

    const char* s1 = "frederic";
    const char* s2 = "anica";
    const char* s3 = "lucas";
    ::max(s1, s2, s3);    // ERROR

}

他说,::max(s1, s2, s3)中出现错误的原因是,对于C字符串,max(max(a,b),c)调用max(a,b),这会创建一个新的临时本地值,该值可能会由函数通过引用返回。

我不明白一个新的本地价值是如何创造的?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-09 14:33:02

对于C字符串,此代码创建一个局部值,即存储地址的局部变量( char const *类型的指针):

std::strcmp(a,b) <0?B: a;

因此,返回对this的引用(使用模板函数)会导致错误。在本例中,模板函数max在C字符串max返回副本后返回对local类型的char const * const &引用。模板函数必须按值而不是按引用返回指针。

需要为指针类型重载模板函数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9206319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档