rmaddy
rmaddy

Reputation: 318814

How can I force a compiler warning with operator==?

This is a follow-on to my earlier question.

I have a bunch of Objective-C code like this:

typedef long DataKey;

DataKey x;
DataKey y;

if (x == y) {
    // do stuff
}

I now have a need to change DataKey to be an object instead of long. If I create the class and do a bunch of global search and replace, my code now is kind of like this:

@interface DataKey : NSObject

DataKey *x;
DataKey *y;

if (x == y) { // uh-oh - this is now bad, I need isEqual: here
}

Since there is no compiler warning to detect using the == operator with two object pointers, I am looking for another solution.

One thought was to use a C++ class and overload the == operator in such a way that the compiler would complain.

I don't know C++ nearly as well as Objective-C. I've been able to write the C++ class and I now have code that actually results in the operator== method being called. Now I need help coming up with a way to tweak the code so I get a compiler warning.

Here's the C++ class:

class DataId {
public:
    DataId();

    bool operator==(const DataId &other);
};

Now I have some Objective-C++ code like this:

DataId x;
DataId y;

if (x == y) { // I need a compiler warning/error here
}

Is there a syntax trick I can come up to cause a compile error/warning on the if statement.

Upvotes: 3

Views: 382

Answers (3)

bstamour
bstamour

Reputation: 7766

You can use static_assert if you have access to C++11:

class DataId {
    // ...

    bool operator==(const DataId& other)
    {
        static_assert(false, "enter error message here.");
        return true;
    }
};

Just don't define operator == at all and the compiler will fail with an error at the point of use.

Upvotes: -1

Karthik T
Karthik T

Reputation: 31952

Just making the operator== undefined and private should trigger an error. But if you want to compare 2 objects I dont see why you dont define the operator== as you need it.

bool operator==(const DataId &other){
    return IsEqual(other);//is this the function you want to compare with?
}

Upvotes: 1

Lily Ballard
Lily Ballard

Reputation: 185681

Have you tried just not defining an operator== at all? I don't think there's an implicit operator== for C++ classes. So your last snippet of code should throw a compiler error if you just leave off the definition of operator==.

Upvotes: 4

Related Questions