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:
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;
}