Re: Opposite of ! operator.
On Nov 22, 2:38 am, Alan Johnson <aw...@yahoo.com> wrote:
jason.cipri...@gmail.com wrote:
If I have:
class Something {
public:
bool operator ! () const;
};
Then I can do:
Something s(...);
if (!s) ...;
My question is, what operator do I need to overload if I want to be
able to define the behavior of this instead:
Something s(...);
if (s) ...; // <-- notice no !
Sorry if the post title was stupid, I couldn't think of a better one.
Thanks,
Jason
As others have mentioned the straightforward approach is to implement
operator bool or operator void *. Each of these has some type
conversion drawbacks that aren't immediately obvious. Safe solutions
exist but it gets complicated quickly. See:http://www.artima.com/cppso=
urce/safebool.html
Thanks guys, that was some interesting info. I've gone with operator
bool.
I have another question. What is the purpose of being able to overload
the unary ! operator? It seems like it would have been less ambiguous
if the rule was convert to bool implicitly then use ! on the resulting
bool, rather than making ! available as an overloadable operator. The
reason I ask is it seems like it's clearer in all cases to just
implement operator bool and not implement operator !.
For example, here is something weird:
class Ambiguous {
public:
operator bool () const { return true; }
bool operator ! () const { return true; }
};
And then I can do:
Ambiguous a;
assert(a && !a); // doesn't read well, does it?
Another weird thing is that it seems that it will use the bool
conversion operator by default if you don't have a ! operator defined:
class A {
public:
operator bool () const { cout << "hi"; return true; }
};
Evaluating "!A();" would print "hi".
So I guess my question is: When would you ever want to override ! but
not bool?
Thanks,
Jason