I have a couple of pure virtual classes, Matrix and Vector. Throughout my code base I try to only create dependencies on them and not their concrete subclasses e.g. SimpleTransformationMatrix44 and SimpleTranslationVector4. The motivation for this is that I can use third party (adapted) classes in place of mine without much trouble.
I would like to overload the arithmetic operators (sourced from here):
T T::operator +(const T& b) const;
T T::operator -(const T& b) const;
T T::operator *(const T& b) const;
I want to declare them in the pure virtual classes so that it is valid to perform the operations on references/pointers to them, the problem being that an abstract class cannot be returned by value. The best solution I can think of is something like this:
std::unique_ptr<T> T::operator +(const T& b) const;
std::unique_ptr<T> T::operator -(const T& b) const;
std::unique_ptr<T> T::operator *(const T& b) const;
Which allows this (without down casts!):
std::unique_ptr<Matrix> exampleFunction(const Matrix& matrix1, const Matrix& matrix2)
{
std::unique_ptr<Matrix> product = matrix1 * matrix2;
return std::move(product);
}
A pointer seems to be the only option in this case since returning a value is invalid and returning a reference is just plain silly.
So I guess my question is: Have I gone off the plot with this idea? If you saw it in some code you were working on would you be thinking WTF to yourself? Is there a better way to achieve this?
First off: Overloading operators is something that applies best to value types. As you have found out, polymorphism doesn’t play well with it. If you are willing to walk on crutches, this might help, though:
If you follow the advice of Stackoverflow’s operator overloading FAQ, you will implement
operator+()as a non-member atop ofoperator+=(). The latter returns a reference. It’s still a problem, because it can only return a base class reference, but as long as you only use it for expressions expecting that, you are fine.If you then templatize
operator+()as DeadMG suggested, you might be able to do what you want:Note that this would catch any
Tfor which no better-matchingoperator+()overload can be found. (This might seem like a good idea — until you forget to include a header and this operator catches thex+y, making the code compile, but silently produce wrong results.) So you might want to restrict this.One way would be to put it into the same namespace as you matrix and vector types. Or you use a
static_assertto ensure only types derived from the two are passed in.