C Implicit Conversions: Clarification
In a recent discussion, the validity of implicit conversions in C has been questioned. Specifically, the issue revolves around whether multiple implicit user-defined conversions are allowed. To shed light on this matter, let's examine the following code:
<code class="cpp">struct A { A( const std::string & s ) {} }; void func( const A & a ) { } int main() { func( "one" ); // error func( A("two") ); // ok func( std::string("three") ); // ok }</code>
As stated in the original question, the first function call results in an error because there is no conversion from a const char * to an A. While a conversion from a string to an A exists, applying this involves multiple conversions, which is not permitted. This is corroborated by the C Standard:
<code class="cpp">4 At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value.</code>
In this case, the presence of two implicit conversions (string to const char and const char to A) violates this rule, leading to a compiler error. Therefore, the assertion that multiple implicit user-defined conversions are prohibited in C is accurate.
The above is the detailed content of Can Multiple Implicit User-Defined Conversions Be Applied in C ?. For more information, please follow other related articles on the PHP Chinese website!