C Implicit Conversions: Clarification
Recently, comments on a previous answer regarding alternative casts in C have prompted questions about the accuracy of implicit conversions. To provide clarification, we will examine the following code segment:
#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 }
Originally, it was asserted that the first function call results in an error because no direct conversion exists from a const char * to an A. However, there is a conversion from a string to an A. Utilizing this conversion would involve more than one step, which is generally prohibited. This assertion is supported by g 4.4.0 and Comeau compilers.
Upon further investigation, the C Standard (12.3.4) sheds light on this matter, stating that at most one user-defined conversion (constructor or conversion function) can be implicitly applied to a single value. This ruling aligns with the observed behavior and clarifies the limitations of implicit conversions.
In summary, only one implicit user-defined conversion is permitted on a single value. In the provided code, the call func("one") fails because it would require multiple implicit conversions, which is not allowed.
The above is the detailed content of Can Implicit Conversions in C Involve Multiple User-Defined Conversions?. For more information, please follow other related articles on the PHP Chinese website!