In C++ there is a construction !! applicable to non bool values to convert it to bool. For instance:
int n = 12;
if ( !!n )
std::<<cout << "n is true";
else
std::<<cout << "n is false";
Is there any restrictions where it can be applied, or which types is applicable: POD, pointers, etc.?
The restriction is that operator! must be defined for the type (and it must yield a type for which operator! is also defined)
It works for any type that can be evaluated in a boolean context. So arithmetic types, pointer types (including pointer-to-(member)(function)), and anything with a conversion to one of those. Plus odds and ends like enum types, std::nullptr_t, and probably something else I've forgotten. 4/3 in C++11 defines what contextually converted to bool means, and that's what the built-in operator! does.
For all of these types, writing if(!!n) is redundant, you can write if(n) with the same meaning. !!n for such types means the same as bool(n) or static_cast<bool>(n);.
It also works for any type with an overloaded operator! that returns a type that can be converted to bool (or that returns a type with operator! overloaded to return bool).
If the leftmost operator! returns a type other than bool, then you might still be able to write if(!!n), but !! doesn't act as a conversion to bool. It acts as a conversion to whatever type is returned.
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