I just came onto a project with a pretty huge code base.
I\'m mostly dealing with C++ and a lot of the code they write uses double negation for their boolean logic.
This may be an example of the double-bang trick, see The Safe Bool Idiom for more details. Here I summarize the first page of the article.
In C++ there are a number of ways to provide Boolean tests for classes.
An obvious way is
operator boolconversion operator.
// operator bool version
class Testable {
bool ok_;
public:
explicit Testable(bool b=true):ok_(b) {}
operator bool() const { // use bool conversion operator
return ok_;
}
};
We can test the class,
Testable test;
if (test)
std::cout << "Yes, test is working!\n";
else
std::cout << "No, test is not working!\n";
However, opereator bool is considered unsafe because it allows nonsensical operations such as test << 1; or int i=test.
Using
operator!is safer because we avoid implicit conversion or overloading issues.
The implementation is trivial,
bool operator!() const { // use operator!
return !ok_;
}
The two idiomatic ways to test Testable object are
Testable test;
if (!!test)
std::cout << "Yes, test is working!\n";
if (!test2) {
std::cout << "No, test2 is not working!\n";
The first version if (!!test) is what some people call the double-bang trick.