Home > Backend Development > C++ > Why Does Implicit Conversion of a Person Object to a String Result in Overload Resolution Failure?

Why Does Implicit Conversion of a Person Object to a String Result in Overload Resolution Failure?

Barbara Streisand
Release: 2024-11-05 11:11:02
Original
576 people have browsed it

Why Does Implicit Conversion of a Person Object to a String Result in Overload Resolution Failure?

Overload Resolution Failure During Implicit Conversion of Object to String

Implicit string conversions are generally discouraged, with an operator overload for Person being a more appropriate solution. However, let's examine the following code to illustrate the issue:

<code class="cpp">#include <string>
#include <ostream>
#include <iostream>

struct NameType {
   operator std::string() { return "wobble"; }
};

struct Person {
   NameType name;
};

int main() {
   std::cout << std::string("bobble");
   std::cout << "wibble";

   Person p;
   std::cout << p.name; // Error occurs here
}</code>
Copy after login

The code compiles without errors when using GCC 4.3.4, giving the output:

<code class="Bash">bobble
wibble</code>
Copy after login

However, attempting to implicitly convert the Person object to a string using << operator fails with overload resolution error:

<code class="Bash">prog.cpp:18: error: no match for ‘operator<<’ in ‘std::cout << p.Person::name’</code>
Copy after login

In this instance, the operator << is overloaded to handle std::string and const char*, however, there isn't a predefined overload that accepts a Person object and implicitly converts it to a string. As a result, the compiler fails to resolve the overload.

To rectify this issue, you should define an explicit operator << for the Person struct as a friend function, allowing the implicit conversion from a Person object to a string to work correctly.

The above is the detailed content of Why Does Implicit Conversion of a Person Object to a String Result in 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