문제

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 the bool you want. From what I see in the link you provided, they do their tests with a double negation, !!.

다른 팁

ok supports operator bool, and C++ has this nice functionality called implicit casting and also promotion, and in this case for the binary shift operator <<, the bool is promoted to an int, and this is then shifted by 1.

In the second case, you've not provided that operator, and hence there is nothing to implicitly convert (and promote) to int, and you get the error. Try calling !notOk before the shift, now there is a bool, which will be promoted.

ok<<1;  // Line#1     is valid
notOK << 1; // Line#2: error: inavlid operand to binary expression ('BoolVer_notOK' and 'int')

This happens because ok is converted to bool implicitly (overloaded operator), whereas notOK doesn't have that operator.

Test out the following code:

  BoolVer_OK ok(true);
  BoolVer_NotOK notOK(true);
  int z = ok<<1;  // is valid
  //notOK << 1; // error: inavlid operand to binary expression ('BoolVer_notOK' and 'int')
  int x = false << 1;
  return 0;

The booleans on the left-side of the shift operator are converted to ints and then shifted.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top