Operator overloading with const instance of the class

Started by
1 comment, last by Chronogeran 7 years, 11 months ago

I have a Vector3 type with overloaded operators bound like so:


r = pEngine->RegisterObjectMethod("Vector3", "Math::Vector3 opAdd(float)", asFUNCTIONPR(Math::operator+, (const Math::Vector3 &, float), Math::Vector3), asCALL_CDECL_OBJFIRST);
r = pEngine->RegisterObjectMethod("Vector3", "Math::Vector3 opAdd_r(float)", asFUNCTIONPR(Math::operator+, (float, const Math::Vector3 &), Math::Vector3), asCALL_CDECL_OBJLAST);
r = pEngine->RegisterObjectMethod("Vector3", "Math::Vector3 opAdd(const Math::Vector3 &in)", asFUNCTIONPR(Math::operator+, (const Math::Vector3 &, const Math::Vector3 &), Math::Vector3), asCALL_CDECL_OBJFIRST);

When the Vector3 instances involved in the + operator are not const, everything works. But when the left operand is const in a Vector3 + Vector3 expression, I get the following script compile error:

ERR : No matching operator that takes the types 'const Math::Vector3' and 'Math::Vector3' found

And when the Vector3 instance is const in a float + Vector3 or Vector3 + float expression, I get the following script compile error:

ERR : No conversion from 'const Math::Vector3' to math type available.

I am using AngelScript version 2.30.0.

Here is the example AngelScript code:


Math::Vector3 vec1;
Math::Vector3 vec2;
Math::Vector3 result;

result = vec1 + 5; // Works
result = 5 + vec1; // Works
result = vec1 + vec2; // Works

const Math::Vector3 constVec;

result = constVec + vec1; // Error 1
result = vec1 + constVec; // Works
result = 5 + constVec; // Error 2
result = constVec + 5; // Error 2

Is there something I am doing wrong?

Advertisement

It's only as wrong as it would be if you tried to do the same thing in C++. The expression 'constVec + vec1' is equivalent to 'constVec.opAdd(vec1)'. opAdd is a method like any, so it may modify the instance. The compiler can't know if it does, especially for an application-registered function, so by default methods are not available for const instances, just like in C++. But like in C++, you can easily enable them: "Math::Vector3 opAdd(float) const".

Ah, of course. I had tried that before posting, but I probably modified the signatures of my native calling convention bindings while I was set up to use the generic ones. Thanks for the reply.

This topic is closed to new replies.

Advertisement