www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - overloading &&, || etc?

reply inteja <inteja nosmalldreams.net> writes:
Newbie question.

Say I want to create my own extended bool class that is as easy to use as the
inbuilt bool (I don't want to simply use an alias or typedef). Below is my
basic class. With the new opAssign the user of the class can say MyBool myBool
= true rather than having to explicitly set the property like myBool.value =
true. Now I want to do the same for && and || operations i.e. I should be able
to say if (myBool1 && myBool2) just as with the inbuilt bool, but this doesn't
yet seem possible (and may never be according to the D docs). Does anyone have
any ideas how I can implement this?

class MyBool
{
    private bool myValue = false;

    this()
    {
    }

    this(bool v)
    {
        myValue = v;
    }

    this(int v)
    {
        myValue = (v == 1) ? true : false;
    }

    this(char[] v)
    {
        myValue = (v == "true" || v == "TRUE") ? true : false;
    }

    public bool value()
    {
        return myValue;
    }

    public bool value(bool v)
    {
        return myValue = v;
    }

    public bool opCall()
    {
        return myValue;
    }

    public void opAssign(bool v)
    {
        myValue = v;
    }

    public bool value(int v)
    {
        return myValue = (v == 1) ? true : false;
    }

    public bool value(char[] v)
    {
        return myValue = (v == "true" || v == "TRUE") ? true : false;
    }

    public char[] toLowerString()
    {
        return myValue ? "true" : "false";
    }

    public char[] toUpperString()
    {
        return myValue ? "TRUE" : "FALSE";
    }
}
Dec 14 2006
parent Lutger <lutger.blijdestijn gmail.com> writes:
inteja wrote:
 Newbie question.
 
 Say I want to create my own extended bool class that is as easy to use as the
 inbuilt bool (I don't want to simply use an alias or typedef). Below is my
 basic class. With the new opAssign the user of the class can say MyBool myBool
 = true rather than having to explicitly set the property like myBool.value =
 true. Now I want to do the same for && and || operations i.e. I should be able
 to say if (myBool1 && myBool2) just as with the inbuilt bool, but this doesn't
 yet seem possible (and may never be according to the D docs). Does anyone have
 any ideas how I can implement this?
What about: if ( myBool1.and(myBool2).or(myBool3) )? You can also overload the & and | operators. But I don't see a case where this would be a good idea.
Dec 14 2006