This may be a silly thing to ask but I am confused with compilation error while trying to use the safe bool idiom while reading this article. Below is my code and I have indicated the lines where i get errors in main() function.
// is OK case
class BoolVer_OK {
bool m_OK;
public:
BoolVer_OK(bool ok) : m_OK(ok){}
operator bool() { return m_OK; }
};
// Not OK Case
class BoolVer_NotOK {
bool m_notOK;
public:
BoolVer_NotOK(bool ok) : m_notOK(!ok){}
bool operator !() const{ reportexecution; return !m_notOK; }
};
main()
{
BoolVer_OK ok(true);
BoolVer_NotOK notOK(true);
ok<<1; // Line#1 is valid
notOK << 1; // Line#2: error: inavlid operand to binary expression ('BoolVer_notOK' and 'int')
return 0;
}
Why we didn't get error at #Line1 while we get at #Line2. Both results in a boolean value before <<
operator.
I don't think the compiler would automatically insert a call to
operator!
and then negate that to get you thebool
you want. From what I see in the link you provided, they do their tests with a double negation,!!
.