Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evaluate an object directly in a boolean context?

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!

like image 254
Philipp Michalski Avatar asked Dec 11 '22 16:12

Philipp Michalski


1 Answers

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.

like image 84
R. Martinho Fernandes Avatar answered Jan 04 '23 18:01

R. Martinho Fernandes