[英]C++ function template overloading
这个例子来自Josuttis的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)
会创建一个新的临时局部值,该函数可以通过引用返回。
我不知道如何创建新的本地价值?
对于C字符串,此代码创建一个本地值,即,一个存储地址(char const *类型的指针)的本地变量:
std :: strcmp(a,b)<0? b:a;
因此,返回对此的引用(使用模板函数)会导致错误。 在这种情况下,在C字符串max
返回一个副本之后,模板函数max
返回对char const * const &
类型的局部引用。 模板函数必须按值而不是引用返回指针。
指针类型需要重载模板函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.