The use of !!
inside if
statement is redundant, as inside an if
a value may be contextually converted to bool even if the casting is marked as explicit
.
However, in an assignment this trick may be a substitute for an explicit cast:
std::error_code ec;
// some code
// bool is_error = ec; // compilation error, operator bool is explicit
bool is_error1 = !!ec; // ok
bool is_error2 = (bool)ec; // better, one may argue
bool is_error3 = static_cast<bool>(ec); // to avoid C-style cast
bool is_error4 = ec.value() != 0; // most verbose, also possible
It might be that the if(!!ec)
is a copy-paste from an assignment expression.
See also: When can I use explicit operator bool without a cast?
A side note: there might be of course a case where this trick is relevant inside if
- in case a type implements operator!
and lacks operator bool
- but this is not the case with std::error_code
.