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

Can Implicit Conversions in C Involve Multiple User-Defined Conversions?

Susan Sarandon
Release: 2024-11-03 16:49:30
Original
534 people have browsed it

Can Implicit Conversions in C   Involve Multiple User-Defined Conversions?

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 &amp; s ) {}
};

void func( const A &amp; a ) {
}

int main() {
    func( "one" );                  // error
    func( A("two") );           // ok
    func( std::string("three") );   // ok
}
Copy after login

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!

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