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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With