Is it possible to have a class object return a true/false value, so I can do something like this:
MyClass a;
...
if (a)
开发者_JAVA技巧 do_something();
I can accomplish (almost) what I want by overloading the ! operator:
class MyClass {
...
bool operator!() const { return !some_condition; };
...
}
main()
MyClass a;
...
if (!a)
do_something_different();
but I haven't found a way to overload what would be the "empty" operator. Of course, using the == operator to check for true/false is also possible, and is in fact what I have been doing so far.
Overload the void * cast operator:
operator void * () const { return some_condition; };
this is how streams work, allowing you to say:
if ( cin ) {
// stream is OK
}
The use of void * rather than bool prevents the cast being used by mistake in some contexts, such as arithmetic, where it would not be desirable. Unless, you want to use it in those contexts, of course.
The obvious solution – providing an implicit conversion to bool
via operator bool
– is a bad idea.
That’s why the standard library uses operator void*
as shown in Neil’s answer.
However, it’s worth pointing out that even this solution has flaws and is therefore no longer considered safe. Unfortunately, coming up with a better solution isn’t trivial …
There’s an article over at Artima that describes the safe bool idiom. For a real library, this is definitely the way to go, since it offers the most robust interface that is hardest to use wrong.
Weird, no one has mentioned the safe bool idiom so far. All the other solutions described so far have drawbacks (which you might or might not care about), all those approaches are described in the article. In a nutshell, the safe bool idiom goes something like this:
class Testable {
typedef void (Testable::*bool_type)() const;
void this_type_does_not_support_comparisons() const {}
public:
operator bool_type() const {
return /* condition here */ ?
&Testable::this_type_does_not_support_comparisons // true value
: 0; // false value
}
};
Try overloading the (bool) operator:
operator bool() { /* ... */ }
精彩评论