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