How to using opCmp

Heromyth bitworld at qq.com
Sat Dec 17 06:06:48 PST 2011


I have defined a opCmp function to overload comparison operators, then how can
I use it correctly?

I can use it like this:
   int b = t1.opCmp(info);
and is it right like this:
   int b = t1 < info;

In my test code, I get different value for b. What can I do?
Thanks for helps.

//=============
//Test code:
//=============
import std.stdio;
import std.conv;
import std.file;
import std.algorithm;
import std.range;
import std.array;
import std.format;
import std.path;
import std.ascii;
import std.utf;
import std.process;

public final class LogLevel
{
    @property public static LogLevel Trace()
    {
        if( m_Trace is null )
            m_Trace = new LogLevel("Trace", 0);
        return m_Trace;
    }
    private static LogLevel m_Trace;

    @property public static LogLevel Info()
    {
        if( m_Info is null )
            m_Info = new LogLevel("Info", 2);
        return m_Info;
    }
    private static LogLevel m_Info;


    public string getName()
    {
        return name;

    }

    private int ordinal;
    private string name;

    public static LogLevel FromString(string levelName)
    {
        if (levelName.empty())
        {
            throw new Exception("levelName");
        }

        return Trace;
    }

	public  int  opCmp(LogLevel level1)
	{
		int result = 0;
		if( this.Ordinal > level1.Ordinal)
			result = 1;
		else if( this.Ordinal == level1.Ordinal)
			result = 0;
		else
			result = -1;
		writefln("result == %d", result);
		return result;
	}

    @property package int Ordinal()
    {
        return this.ordinal;
    }


    private this(string name, int ordinal)
    {
        this.name = name;
        this.ordinal = ordinal;
    }
}


int main(string[] args)
{
    LogLevel t1 = LogLevel.Trace;
    LogLevel t2 = LogLevel.Trace;
    LogLevel info = LogLevel.Info;
	int a = t1 > t2;
	writefln("a == %d", a);

	int b = t1.opCmp(info);
	writefln("b == %d", b);

	b = t1 < info;
	writefln("b == %d", b);

	b = t1 > info;
	writefln("b == %d", b);

    return 0;
}
//=============


More information about the Digitalmars-d-learn mailing list