C Implicit Conversions: Understanding User-Defined Conversion Rules
In light of recent feedback on a previous response, it's essential to clarify the understanding of implicit conversions in C .
Consider the following code snippet:
<code class="c++">#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>
The first function call results in an error because there is no direct conversion from a const char* to an A. Although there is a conversion from a string to an A, applying this would require multiple conversions, which is not allowed.
The C Standard (SC22-N-4411.pdf) provides the answer in section 12.3.4 titled 'Conversions':
"4 At most one user-defined conversion (constructor or conversion function) is implicitly applied to a single value."
This means that only one implicit user-defined conversion (either a constructor or a conversion function) can be applied to a single value during implicit type conversions or initialization.
In the given code, the first function call, func("one"), attempts to use an implicit conversion from the const char* "one" to A, but it fails because this requires two conversions (one from const char* to std::string, and another from std::string to A). The other two function calls are valid because they involve only one implicit conversion each.
The above is the detailed content of Why Does C Allow Only One User-Defined Conversion During Implicit Type Conversions?. For more information, please follow other related articles on the PHP Chinese website!