mardi 19 décembre 2023

Overloaded Templates and non-template functions

I encountered a problem about "Overloaded Templates and non-template functions".

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

// print any type we don't otherwise handle
template <typename T>
string debug_rep(const T &t) {
    ostringstream ret;
    ret << t; // uses T's output operator to print a representation of t
    return ret.str(); // return a copy of the string to which ret is bound
}

// print pointers as their pointer value, followed by the object to which the pointer pointsv
template <typename T>
string debug_rep(T *p) {
    ostringstream ret;
    ret << "pointer: " << p;  // print the pointer's own value
    if (p) {
        ret << " " << debug_rep(*p);  // print the value to which p points
    } else {
        ret << " null pointer";  // or indicate that the p is null
    }
    return ret.str();  // return a copy of the string to which ret is bound
}

string debug_rep(char * p) {
    return debug_rep((string)p);
}

string debug_rep(const char * p) {
    return debug_rep((string)p);
}

int main() {
    string debug_rep(const string& s);
    const char * cp = "hello";
    cout << debug_rep(cp) << endl;

    return 0;
}

string debug_rep(const string& s) {
    return '"' + s + '"';
}

In the book "C++ Primer", they say the cout << debug_rep(cp) << endl; in main function will call debug_rep(const char * p). However, through my test, it actually calls debug_rep(const string& s). So, I wonder why this happened.

Aucun commentaire:

Enregistrer un commentaire