C++ Primer (5th ed.) : Is “16.3 Overloading and Templates” wrong in all its “more specialized” examples?

前端 未结 2 464
孤城傲影
孤城傲影 2021-01-15 18:49

Section 16.3 of C++ Primer (5th edition) - Overloading and Templates -, teaches the function matching procedure in the presence of candidate function template(s) instantiati

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-15 19:31

    You're given these declarations:

    using std::string;
    template  string debug_rep(const T &); /* 1 */
    template  string debug_rep(T *);       /* 2 */
    

    In the invocation

    string s("SO");
    debug_rep(&s);
    

    the &s produces a string*, which can only match the T const& of (1) when T is string*. For the T* in (2), there is a match for T bound to string. So, provided your quoting is correct, the book is wrong about

    debug_rep(const string *&)
    

    being a possible instantiation: there is no such.

    The instantiation resulting from T = string* would instead be

    debug_rep( string* const& )
    

    But which instantiation will be called?

    As a general rule the simplest match is superior, but I never manage to remember the exact rules, so, I ask Visual C++ (because its typeid(T).name() produces readable type names by default):

    #include 
    #include 
    #include 
    using namespace std;
    
    template< class T >
    struct Type {};
    
    template  auto debug_rep( T const& )   // 1
        -> string
    { return string() + "1 --> T = " + typeid(Type).name(); }
    
    template  auto debug_rep( T* )         // 2
        -> string
    { return string() + "2 --> T = " + typeid(Type).name(); }
    
    auto main() -> int
    {
        string s( "SO" );
        cout << debug_rep( &s ) << endl;
        cout << "The type 'int const' is shown as " << typeid(Type).name() << endl;
    }
    

    And it says:

    2 --> T = struct Type,class std::allocator > >
    The type 'int const' is shown as struct Type
    

    And so on for your second and third examples: apparently the author got some mixup regarding const.

提交回复
热议问题