简体   繁体   English

C ++函数模板重载

[英]C++ function template overloading

This example is from C++ templates book by Josuttis : 这个例子来自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

}

He says that the reason for error in ::max(s1, s2, s3) is that for C-strings max(max(a,b),c) calls max(a,b) that creates a new temporary local value that may be returned by the function by reference. 他说::max(s1, s2, s3)错误的原因是对于C字符串max(max(a,b),c)调用max(a,b)会创建一个新的临时局部值,该函数可以通过引用返回。

I am not getting how a new local value is getting created ? 我不知道如何创建新的本地价值?

For C-strings, this code creates a local value, ie, a local variable that stores an address (pointer of type char const *): 对于C字符串,此代码创建一个本地值,即,一个存储地址(char const *类型的指针)的本地变量:

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

Hence returning a reference to this (using the template functions) leads to an error. 因此,返回对此的引用(使用模板函数)会导致错误。 In this case the reference of type char const * const & to a local is returned by the template function max after the C-string max has returned a copy. 在这种情况下,在C字符串max返回一个副本之后,模板函数max返回对char const * const &类型的局部引用。 The template functions have to return pointers by value instead of reference. 模板函数必须按值而不是引用返回指针。

The template functions need to be overloaded for pointer types. 指针类型需要重载模板函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM