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)
,创建一个新的临时局部值可能会被函数返回的引用。
我没有得到如何创建一个新的本地值?
您确定您正确地复制了本书中的代码吗?我认为'inline char const * max'应该是'inline char const * const&max' – 2012-02-09 06:40:41
'inline T const&max(T const&a,T const&b,T const&c)'的最后一个返回将仍然返回一个对本地值(指针),一旦max完全返回就会停止存在。 – devil 2012-02-09 07:24:39
杰西,这个例子来自Josuttis的网站......(http://www.josuttis.com/tmplbook/)...它的'basics/max3a.cpp' – amneet 2012-02-09 16:11:26