Reputation: 9523
I mean, we all know that there is the negation logical operator !
, and it can be used like this:
class Foo
{
public:
bool operator!() { /* implementation */ }
};
int main()
{
Foo f;
if (!f)
// Do Something
}
Is there any operator that allows this:
if (f)
// Do Something
I know it might not be important, but just wondering!
Upvotes: 3
Views: 238
Reputation: 131799
Since operator bool()
in itself is pretty dangerous, we usually employ something called the safe-bool idiom:
class X{
typedef void (X::*safe_bool)() const;
void safe_bool_true() const{}
bool internal_test() const;
public:
operator safe_bool() const{
if(internal_test())
return &X::safe_bool_true;
return 0;
}
};
In C++11, we get explicit conversion operators; as such, the above idiom is obsolete:
class X{
bool internal_test() const;
public:
explicit operator bool() const{
return internal_test();
}
};
Upvotes: 3
Reputation: 385194
You can declare and define operator bool()
for implicit conversion to bool
, if you're careful.
Or write:
if (!!f)
// Do something
Upvotes: 7