operator overloading order of operands


Hi. I've been trying to overload operators in such a way that, for example:

(object) + (native type) = (modified object)

and

(native type) + (object) = (modified object)

The object in question uses a template to determine the type of its data members. I can get the first form working (object + native) by using overloaded operator member function, but I am having difficulty figuring out how to get the other form to work. I tried declaring the overloaded operator as a global, but my compiler informed me that it could not match the expression to the defined overloaded operator. I suspect that the fact that my class uses templates and the global overloaded operator does not 'know' what type the class's template is, within the context of the expression, is the issue.

So, in C++ how does one best account for and differentiate operand order when doing operator overloading? How can I make it so that I can have a template-using class that can be placed in expressions with native types even if the native type comes first in the expression?

Note that the global operator overloading behavior above works just fine if either the class doesn't use templates (already defines the types of its members), or if a corresponding type-specific global overloaded operator exists for any given type used in instances of the template class.

I await your reply, and I thank you for your time.

Ok, I figured it out.

I just had to use a template declaration with multiple parameters, because I was trying to do this:

Object<double> + int = Object<double>

when my template declaration for the overloaded operator only had the form:

template <typename N>
operator+(const Object<N>, const N)

Thus I needed to change the template declaration to "template <typename N1, typename N2> operator+(const Object<N1>, const N2)", and vice versa for the opposite operand order.
Topic archived. No new replies allowed.