1

Probably this means that I have misunderstood the meaning of explicit in general, but with specific example below, what allows a std::optional to be used as a conditon of an if, if its conversion operator to bool is explicit?

#include <iostream>
#include <optional>

int main() {
    std::optional<int> x;
    if (x)
        std::cout << x.value();
    else
        std::cout << "nothing";
}
Enlico
  • 23,259
  • 6
  • 48
  • 102
  • 3
    `if (x)` is one of the contexts that counts as explicit conversion to bool. See https://en.cppreference.com/w/cpp/language/implicit_conversion#Contextual_conversions – M.M Feb 12 '21 at 22:24
  • Oh, ok, so it's what's named _contextual conversion_ [here](https://en.cppreference.com/w/cpp/language/implicit_conversion). It looks to me that it says that the condition of an `if` is implicitly converted to `bool` if it can be explicitly converted to `bool`. Am I misunderstanding it? – Enlico Feb 12 '21 at 22:30
  • Yes you're misunderstanding it – M.M Feb 12 '21 at 22:44

0 Answers0