Overloaded Templates and Conversions

There’s one case we haven’t covered so far: pointers to C-style character strings and string literals. Now that we have a version of debug_rep that takes a string, we might expect that a call that passes character strings would match that version. However, consider this call:

cout << debug_rep("hi world!") << endl; // calls debug_rep(T*)

Here all three of the debug_rep functions are viable:

debug_rep(const T&), with T bound to char[10]

debug_rep(T*), with T bound to const char

debug_rep(const string&), which requires a conversion from const char* to string

Both templates provide an exact match to the argument—the second template requires a (permissible) conversion from array to pointer, and that conversion ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.