2012-02-09 142 views
1

这个例子是C++模板书约祖蒂斯:C++函数模板重载

#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),创建一个新的临时局部值可能会被函数返回的引用。

我没有得到如何创建一个新的本地值?

+0

您确定您正确地复制了本书中的代码吗?我认为'inline char const * max'应该是'inline char const * const&max' – 2012-02-09 06:40:41

+1

'inline T const&max(T const&a,T const&b,T const&c)'的最后一个返回将仍然返回一个对本地值(指针),一旦max完全返回就会停止存在。 – devil 2012-02-09 07:24:39

+0

杰西,这个例子来自Josuttis的网站......(http://www.josuttis.com/tmplbook/)...它的'basics/max3a.cpp' – amneet 2012-02-09 16:11:26

回答

0

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

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

因此,返回对此的引用(使用模板函数)会导致错误。在这种情况下,在C字符串max已经返回副本之后,char const * const &类型的引用返回给本地模板函数max。模板函数必须通过值而不是引用返回指针。

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