overloading &&, || etc?

inteja inteja at nosmalldreams.net
Thu Dec 14 00:49:57 PST 2006


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";
    }
}


More information about the Digitalmars-d-learn mailing list