I have two classes, one which inherits from the other. The relevant part of the base class is as follows (obviously this class has ctors, a dtor, etc., and particularly an operator[]
, but I thought those irrelevant to the matter at hand):
#include <array>
template < class T, unsigned int N >
class Vector
{
public:
template < class U, unsigned int M > friend Vector< U, M > operator+ ( const Vector< U, M >&, const Vector< U, M >& );
template < class U, unsigned int M > friend std::ostream& operator<< ( std::ostream&, const Vector< U, M >& );
};
The derived class (again, obviously I've taken out those parts which I thought irrelevant):
#include "Vector.h"
template < class T, unsigned int N >
class Polynomial
: public Vector< T, N >
{
public:
template < class U, unsigned int M > friend std::ostream& operator<< ( std::ostream&, const Polynomial< U, M >& );
};
(Note: The friend functions use different letters for the templates than the classes do, because otherwise gcc complains about "shadowing". The logic is the same, though.)
Vector
s print out one way (e.g. < 3, 5, 1 >
); Polynomial
s print out another (e.g. 3 x^2 + 5 x + 1
).
This causes a problem, though. When I go to add two Polynomial
s together, the compiler uses template < class U, unsigned int M > Vector< U, M > operator+ ( const Vector< U, M >&, const Vector< U, M >& )
, which of course returns a Vector
. Therefore, if I try to do something like std::cout << poly1 + poly2;
, the resultant display is in the wrong format.
I would like to modify template < class U, unsigned int M > Vector< U, M > operator+ ( const Vector< U, M >&, const Vector< U, M >& )
such that it will detect the actual data types of its parameters, and cast the return value accordingly (e.g. return a Polynomial
if two Polynomial
s are passed to it). I would like to do this, if possible, without operator+
knowing about each and every possible subclass of Vector
(I think this is probably a legitimate desire?), and without making a new operator+
function for each subclass (since I also have several other overloaded operators, and would like to avoid copying almost exactly the same code ten times for each derived class).
I know that this is possible (and, in fact, relatively easy) in Python. Does C++ support such a thing?