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
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 tobool
and is well-formed if and only if the declarationbool t(e);
is well-formed, for some invented temporary variablet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With