Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Where does C++ standard says that multiple user-defined conversions is not allowed

I searched a a lot in the C++20 standard for any sentence that says "mutiple user-defined conversions are not allowed in a sequence". But I find nothing that prohibits that.

Consider the following example:

struct A { A(std::string); };

int main(void){
    A a = "foo";
}

The compiler gives me the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

error: conversion from 'const char [4]' to non-scalar type 'A' requested

At first glance, the compiler doesn’t said that there are multiple user-defined conversions are applied. But I see that there’s a conversion from const char [4] to std::string, then from std::string to A. Right? But I don’t understand why this conversion is failed. So where C++ standard prohibits such conversions?

>Solution :

The paragraph you’re looking for is §11.4.8.1 [class.conv.general]/4, which says:

At most one user-defined conversion (constructor or conversion
function) is implicitly applied to a single value. [Example 1:

struct X {
  operator int();
};

struct Y {
  operator X();
};

Y a;
int b = a;      // error: no viable conversion (a.operator X().operator int() not considered)
int c = X(a);   // OK: a.operator X().operator int()

— end example]

One possible solution for your program is to explicitly convert this "foo", which is of type const char [4] into a std::string; therefore you now have only one user-defined conversion from std::string to A which is performed by the converting constructor A::A(std::string);.

You can do this by using the operator ""s which returns std::string:

struct A { A(std::string); };
using namespace std::string_literals;

int main(void){
    A a = "foo"s;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading