"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Beyond `if` Statements: Where Else Can a Type with an Explicit `bool` Conversion Be Used Without Casting?

Beyond `if` Statements: Where Else Can a Type with an Explicit `bool` Conversion Be Used Without Casting?

Published on 2024-11-08
Browse:957

Beyond `if` Statements: Where Else Can a Type with an Explicit `bool` Conversion Be Used Without Casting?

Contextual Conversion to bool Allowed Without a Cast

Your class defines an explicit conversion to bool, enabling you to use its instance 't' directly in conditional statements. However, this explicit conversion poses the question: where else can 't' be used as a bool without a cast?

Contextual Conversion Scenarios

The C standard specifies four main scenarios where a value can be contextually converted to bool:

Statements:

  • if, while, for, do-while statements

    if (t)
      /* statement */;

Expressions:

  • Negation (!), logical AND (&&), logical OR (||), ternary operator (?)

    !t
    t && t2

Compile-Time Tests:

  • static_assert, noexcept, explicit, if constexpr (requires constexpr conversion operator)

    static_assert(t);
    noexcept(t)

Algorithms and Concepts:

  • NullablePointer, predicate or comparator arguments in STL algorithms

    NullablePointer T
    std::remove_if(first, last, [&](auto){ return t; });

Additional Notes:

  • Narrowing conversions from integers other than 0 and 1 are not permitted in compile-time tests (C 26 onwards).
  • Mixing const and non-const conversion operators can lead to confusion.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3