Reputation: 606
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!
Upvotes: 4
Views: 4641
Reputation: 158599
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.
Upvotes: 2
Reputation: 234654
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.
Upvotes: 13