I have a template class which defines operators, that works on the template parameters.
I have another class that inherits from this class, and I want the operators to be inherited of course.
Consider this:
template <typename T>
class A
{
public:
A(const T& x) : x_(x) {}
A operator-(const A& other)
{
A r(*this);
r.x_ -= other.x_;
return r;
}
T x() const { return x_; }
private:
T x_;
};
template <typename T>
class B : public A<T>
{
// additional stuff here
};
I cannot seem to use any of the operators declared in A for the objects of type B.
Example:
int main()
{
// Fine
A<int> a(5);
A<int> b(2);
A<int> c = a - b;
std::cout << c.x() << std::endl;
// Won't compile :(
B<int> d(5);
B<int> e(2);
B<int> f = d - e;
std::cout << f.x() << std::endl;
return 0;
}
Will trigger the following error: error: conversion from ‘A’ to non-scalar type ‘B’ requested
Is there any way this can work? I really want to avoid re-writing all the code (which would be exactly the same) in class B.
Thanks !
The issue is not with calling the operator, but constructing a
Bfrom the return value which is anA.If
Bdoes not contain any data other than in its base classA, you can provide a constructor for aBfrom anA:If
Bdoes contain its own data, then surely you need to implement theoperator-to handle those data fields?