Apologies if this has been asked and answered before, but I've been searching for an understandable solution now for hours with no joy.
I'm trying to implement a simple class hierarchy with operator overloads defined within the base class (since these will not differ between the various derived classes). However, since most of these will need to return a new object of whatever derived class we're in the context of, I'm assuming they need to be declared as a templated method, however, when I attempt to compile doing this, the linker gives me an 'Unresolved external symbol' error ...
By way of an example:
/// This is in the class header file
class Base
{
// Declare all the base storage and methods ...
public:
template<class T>
friend T operator+(const T& lhs, const T& rhs);
// .... other stuff in here.
}
/// Then in the implementation file
T operator+ (const T& lhs, const T& rhs)
{
return T(lhs->m_1 + rhs->m_1, lhs->m_2);
}
I was hoping that this would lead to my being able to declare derived objects thus:
class Derived : public Base
{
// ... Add the derived class functionality
// -- Question: Do I need to do anything in here with operator+ ???
}
Derived A();
Derived B();
Derived C = A + B;
Is the desired outcome, but short of defining the operators within each individual derived class, I cannot see a way I can implement this in C++ since the Template approach leads to the linker error.
Am I missing something blindingly obvious and fundamental, or is there simply no easy way of doing this in C++?