views:

307

answers:

3

I'm porting a class which implements IEquatable<T> and IComparable<T> and overrides ==, !=, < and > from C# into C++/CLI. So far I have:

Header:

virtual bool Equals(Thing other);
virtual int CompareTo(Thing other);

static bool operator == (Thing tc1, Thing tc2);
static bool operator != (Thing tc1, Thing tc2);
static bool operator > (Thing tc1, Thing tc2);
static bool operator < (Thing tc1, Thing tc2);

Source file:

bool Thing ::Equals(Thing other)
{
    // tests equality here
}

int Thing ::CompareTo(Thing other)
{
    if (this > other) // Error here
        return 1;
    else if (this < other)
        return -1;
    else
        return 0;
}

bool Thing ::operator == (Thing t1, Thing t2)
{
    return tc1.Equals(tc2);
}

bool Thing ::operator != (Thing t1, Thing t2)
{
    return !tc1.Equals(tc2);
}

bool Thing::operator > (Thing t1, Thing t2)
{
    // test for greater than
}

bool Thing::operator < (Thing t1, Thing t2)
{
    // test for less than
}

I'm not sure why the original tested equality in the interface and compared things in the operator, but I'm trying to preserve the original structure.

Anyway, I get a compilation error at the marked line: "error C2679: binary '>' : no operator found which takes a right-hand operand of type 'ThingNamespace::Thing' (or there is no acceptable conversion)", and a corresponding error two lines below. Why isn't it picking up the existence of the overloaded operator?

+6  A: 

This is a pointer, you'll need to dereference it.

if ((*this) > other)
    return 1;
else if ((*this) < other)
    return -1;
else
    return 0;
arul
+1  A: 
return (*this) == other ? 0 : ((*this) > other ? 1 : -1);
A: 

as arul said, you need to dereference the this keyword, but on a side note, you should probably use const references in your function paramaters instead of passing the object since:

-C++ passes all objects by value, not by reference(which is what happens in C#), so using references reduces the overhead.

-It'll let you use functions from the standard library such as std::sort without needing to explicitly specify a new comparison operator

Dasuraga