Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit conversion operator bool

Tags:

c++

I have the following code

  class C
    {
    public:
        C(bool v_):v(v_){};
        explicit operator bool() const {return v;}
        bool v = false;    
    };

 int main(){
  C a{true};
  C b{false};
  // C d = true; // doesn't compile, since requires explicit conversion
  C d = static_cast<bool>(true); // fine

  if(a || b) std::cout << "conversion happened!" << std::endl; // why it doesn't require explicit conversion here?

 }

It outputs "conversion happened!". My question is why || is considered to be a explicit conversion?

Edit

  // C d = true; // actually this line compiles because of the constructor
like image 645
Allanqunzi Avatar asked Feb 05 '23 23:02

Allanqunzi


1 Answers

From [expr.log.or]:

The operands are both contextually converted to bool

Contextual conversion to bool is allowed to use explicit conversions. That's the point of the concept of "contextuality": The explicit conversion is allowed precisely when it makes sense, and not otherwise, so you don't accidentally form arbitrary integral or pointer values from the bool conversion, but when you actually ask for a bool, you get it.

See [conv]/4 for details:

Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t

like image 126
Kerrek SB Avatar answered Feb 17 '23 17:02

Kerrek SB