I have two classes, Base and Derived. Base defines an operator (here operator +) and I want to use it between instances of the Derived classes, but I can\'t manage to work this
This is a common use case for the curriously recurring template pattern. An example would be
template<typename T>
class Base
{
public:
Base(int X) { x = X; }
friend T operator+(const Base& lhs, const Base& rhs)
{
return T(lhs.x + rhs.x);
}
int x;
};
class Derived : public Base<Derived>
{
public:
Derived(int arg) : Base(arg) { }
using Base::Base;
};
int main()
{
Derived der1(1);
Derived der2(2);
Derived der3 = der1 + der2;
return 0;
}
This would behave like so.
Friend name injection (or Barton Nackman trick) is used to generate a function upon instantiation of a templated type. The above is a rough sketch of what a design could be, but I should walk you through the process of calling the + operator.
der1
and der2
are converted to references to base class+
is selected (even if it was in a different namespace, argument dependent lookup would kick in and we would have resolution)The operator constructs a T
which in this case has type Derived
out of the sum
(lhs.x + rhs.x)
That object is used to initialize der3