Home > Backend Development > C++ > Why Does Streaming an Object with Implicit Conversion to String Cause Overload Resolution Failure?

Why Does Streaming an Object with Implicit Conversion to String Cause Overload Resolution Failure?

Susan Sarandon
Release: 2024-11-05 00:57:01
Original
376 people have browsed it

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>
Copy after login

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’
Copy after login

Root Cause

The overload set does not include the desired overload due to a combination of factors:

  • Template Instantiation: The desired overload is an instantiation of a template function with several template parameters.
  • Implicit Conversion Prohibition: The implicit conversion to string (NameType::operator std::string) prevents the desired overload from being considered.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template