Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why overload true and false instead of defining bool operator?

I've been reading about overloading true and false in C#, and I think I understand the basic difference between this and defining a bool operator. The example I see around is something like:

public static bool operator true(Foo foo) {
  return (foo.PropA > 0);
}
public static bool operator false(Foo foo) {
  return (foo.PropA <= 0);
}

To me, this is the same as saying:

public static implicit operator bool(Foo foo) {
  return (foo.PropA > 0);
}

The difference, as far as I can tell, is that by defining true and false separately, you can have an object that is both true and false, or neither true nor false:

public static bool operator true(Foo foo) { return true; }
public static bool operator false(Foo foo) { return true; }
//or
public static bool operator true(Foo foo) { return false; }
public static bool operator false(Foo foo) { return false; }

I'm sure there's a reason this is allowed, but I just can't think of what it is. To me, if you want an object to be able to be converted to true or false, a single bool operator makes the most sense.

Can anyone give me a scenario where it makes sense to do it the other way?

Thanks

like image 965
Joe Enos Avatar asked Apr 19 '10 21:04

Joe Enos


People also ask

Which operator is overloaded for cin operation?

Notes: The relational operators ( == , != , > , < , >= , <= ), + , << , >> are overloaded as non-member functions, where the left operand could be a non- string object (such as C-string, cin , cout ); while = , [] , += are overloaded as member functions where the left operand must be a string object.

Which operator can not be overloaded in c++ 1 point?

Dot (.) operator can't be overloaded, so it will generate an error.

Do I have to overload !=?

NO. There is no such requirement that you Must overload !=


2 Answers

As the docs say, overloading true and false is intended to support (nullable) database-types (Yes/No, Y/N, 0/1, etc).

And of course you can define them inconsistently, as with any operator. It is your responsibility to return something sensible. The compiler goes no further than requiring neither or both.

like image 186
Henk Holterman Avatar answered Oct 27 '22 19:10

Henk Holterman


I had no idea these operators existed. That means you can implement the self-negation paradox:

public class ThisClassIsFalse
{
    public static bool operator true(ThisClassIsFalse statement)
    {
        return statement ? false : true;
    }

    public static bool operator false(ThisClassIsFalse statement)
    {
        return statement ? true : false;
    }
}

So now we know the true solution to this classic paradox... StackOverflowException.

like image 28
Dan Bryant Avatar answered Oct 27 '22 18:10

Dan Bryant