Home > Backend Development > C++ > body text

Why Does C Allow Only One User-Defined Conversion During Implicit Type Conversions?

Patricia Arquette
Release: 2024-11-01 01:14:28
Original
538 people have browsed it

Why Does C   Allow Only One User-Defined Conversion During Implicit Type Conversions?

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!