Home > Article > Backend Development > Can Multiple Implicit Conversions Be Applied in a Single Operation in C ?
Implicit Conversions in C
In recent discussions on implicit conversions in C , questions have arisen about the applicability of multiple conversions in a single operation. To elucidate this concept, let's examine the following code:
<code class="cpp">#include <string> 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 initially stated, the first function call is an error because there is no direct conversion from a const char* to an A. While a conversion from string to A exists, utilizing it would require two consecutive conversions.
According to the C Standard (SC22-N-4411.pdf), section 12.3.4 titled 'Conversions':
"At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value."
This implies that in the given code, the compiler cannot implicitly apply both the constructor for A(const std::string &) and the implicit conversion from const char* to std::string (which is then converted to an A) to the argument "one".
Therefore, the original assertion that the first function call would result in an error is correct. The C Standard explicitly states that only one implicit user-defined conversion is allowed, preventing the compiler from performing the necessary steps to satisfy the function's parameter type.
The above is the detailed content of Can Multiple Implicit Conversions Be Applied in a Single Operation in C ?. For more information, please follow other related articles on the PHP Chinese website!