4

I want to evaluate an instance of some class in a boolean context. Or to be clearer, i want to define how the object reacts if its used directly in a boolean context.
Here an example:

class Foo 
{
  int state;
  Foo(): state(1) {}
  bool checkState()
  {
    return (state >= 0);
  }
  void doWork() 
  { 
    /*blah with state*/
  }
};

int main()
{
  Foo obj;
//while(obj.checkState())  //this works perfectly, and thats what i indent to do!
  while(obj)               //this is what want to write
    obj.doWork();
  return 0;
}

Ok, its just a nice to have :-), but is this possible at all? If yes, how?

Thanks!

2 Answers2

12

Use an explicit conversion operator to bool:

explicit operator bool() const { return (state >= 0); }

This does exactly what you want: define what happens when the object is evaluated in a boolean context.

If you have an older compiler, you cannot use explicit, and that is bad because operator bool() (without explicit) can end up used unwantingly in non-boolean contexts. In that case, use the safe bool idiom instead.

R. Martinho Fernandes
  • 209,766
  • 68
  • 412
  • 492
  • ok i tried this and got the error "only declarations of constructors can be 'explicit'". I assume to have an "old" compiler with GCC 4.1.2? I am reading your "safe bool idiom" right now. – Philipp Michalski Mar 22 '13 at 14:44
  • Yes, GCC 4.1.2 does not support this. IIRC you need at least 4.5 (and the `-std=c++0x` flag) – R. Martinho Fernandes Mar 22 '13 at 14:47
  • OMG, this idiom is just a pain in the a** for new OO programmers :-D . I actually have an abstract base class, so i went for the way of reusable testable_with_virtual method, but i got stuck with the problem, that within the code i copied, there is the error "safe_bool_base::this_type_does_not_support_comparisons() const' is protected" although its used in a derived class. – Philipp Michalski Mar 22 '13 at 15:32
1

You can use operator bool():

explicit operator bool() const
{
    return (state >=0) ;
}

As pointed out you want to use explicit to prevent this being used in an integer context. Also main should return an int.

Community
  • 1
  • 1
Shafik Yaghmour
  • 143,425
  • 33
  • 399
  • 682