Home >Backend Development >C++ >Why Does Streaming an Object with Implicit Conversion to String Cause Overload Resolution Failure?
Overload Resolution Failure When Streaming Object via Implicit Conversion to String
Issue Description
Implicit conversion to string is generally discouraged, and overloading the output operator (<<) for user-defined types is a recommended approach instead. However, code involving implicit conversion and object streaming may result in overload resolution ambiguity.
Consider the following example:
<code class="cpp">struct NameType { operator std::string() { return "wobble"; } }; struct Person { NameType name; }; int main() { std::cout << "bobble"; std::cout << "wibble"; Person p; std::cout << p.name; }</code>
Error Message
Compiling this code with GCC 4.3.4 produces the following error:
prog.cpp: In function ‘int main()’: prog.cpp:18: error: no match for ‘operator<<’ in ‘std::cout << p.Person::name’
Root Cause
The overload set does not include the desired overload due to a combination of factors:
ADL Restriction
Argument-dependent lookup (ADL) is not directly involved in this issue. ADL is a compile-time feature that applies when the compiler is resolving a function call. In this case, the implicit conversion to string is performed by the compiler without any function call involved.
The above is the detailed content of Why Does Streaming an Object with Implicit Conversion to String Cause Overload Resolution Failure?. For more information, please follow other related articles on the PHP Chinese website!