Home  >  Article  >  Backend Development  >  Why Does Overload Resolution Fail with Implicit Conversion to `std::string` in C ?

Why Does Overload Resolution Fail with Implicit Conversion to `std::string` in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 06:26:02584browse

Why Does Overload Resolution Fail with Implicit Conversion to `std::string` in C  ?

Overload Resolution Failure with Implicit Conversion

When attempting to stream an object using implicit conversion to string, an overload resolution failure can occur. This is illustrated by the following code, which defines a struct with an implicit conversion to string and a function to stream an object to standard output:

<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;
}</code>

When compiled with GCC 4.3.4, this code yields the following error:

prog.cpp:18: error: no match for ‘operator<<’ in ‘std::cout << p.Person::name’

This error occurs because the free function operator<<(ostream&, string const&) is not considered in the overload set. This is due to a combination of the desired overload being a template instantiation and ADL (Argument Dependent Lookup).

C 98 standard section 14.8.1/4 states that implicit conversions are performed on a function argument to convert it to the type of the corresponding function parameter only if the parameter type contains no template-parameters that participate in template argument deduction. In this case, all of the arguments to the desired overload contain template-parameters that participate in template argument deduction, so none of them can get their value from an implicit conversion.

Therefore, the overload resolution fails and the error is reported.

The above is the detailed content of Why Does Overload Resolution Fail with Implicit Conversion to `std::string` in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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