Pochi
Pochi

Reputation: 2196

Use of `this` in operators

I have something like this:

CLASS CLASS::operator|(CLASS& right) {
    return binop(*((CLASS*) this), right, OP_OR);
}

CLASS is just some class. binop's prototype is

CLASS binop(CLASS& left, CLASS& right, OP op);

This all works fine and compiles using Visual C++ 2010 but fails in g++ with an error:

someheader.h: In member function 'void CLASS::set(int64_t)':
someheader.h:469:29: error: no match for 'operator|' in '*(CLASS*)this | CLASS(bit)'
someheader.h:469:29: note: candidate is:
someheader.h:376:1: note: CLASS CLASS::operator|(CLASS&)
someheader.h:376:1: note:   no known conversion for argument 1 from 'CLASS' to 'CLASS&'

Now, I'm having problems just passing the current object (*this) as some parameter, so I explicitly cast out it to remove the const qualifier on the pointer, which works fine and seems to trick the Visual C++ compiler to accept it as a normal pointer. g++ doesn't seem to like this. If I remove the cast, it still give me an error since this is const-qualified. What I do with the left- and right-hand size of the operators requires that both are mutable.

From what I can gather, it seems that there's an issue with me passing some object and converting it to a reference in the function call... Which doesn't make much sense to me. Any suggestions?

Upvotes: 1

Views: 240

Answers (2)

Qaz
Qaz

Reputation: 61910

You're calling operator| something like this:

int bit = 0x02;
CLASS result = *this | (CLASS)bit;

Your operator takes a reference.

CLASS CLASS::operator| (CLASS &right);

To solve this for GCC, I found that either calling it like this:

CLASS result = *this | (CLASS &)bit;

or defining the operator like this:

CLASS CLASS::operator| (CLASS &&right); //C++11

Both caused it to return the correct result back. I can't guarantee one or the other is the solution though.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283634

Visual Studio violates the standard here.

Your right-hand argument is a temporary, and according to the rules of C++, a temporary cannot match a non-const reference.

Upvotes: 6

Related Questions