Home > Backend Development > C++ > Can Multiple Implicit User-Defined Conversions Be Applied in C ?

Can Multiple Implicit User-Defined Conversions Be Applied in C ?

Susan Sarandon
Release: 2024-10-31 22:09:02
Original
1062 people have browsed it

Can Multiple Implicit User-Defined Conversions Be Applied in C  ?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template