I've been asking myself if it's possible to create a base class which has operator-overloads which the child-class(es) could use.
Example (with Template):
#include <cassert>
template<typename T>
struct Base {
T value {};
Base& operator=(const T& newVal) { this->value = newVal; return *this; }
};
template<typename T>
struct Child : Base<T> {
};
int main() {
Child<int> ch {};
assert(ch.value == 0);
ch = 10; // compilation error here
assert(ch.value == 10);
}
I tried it myself with a Compile-Error. What should I do if I want to do that? Is this even possible or do I have to use virtual and override it (or whatever is possible)?
Error C2679: binary 'operator' : no operator found which takes a right-hand operand of type 'type' (or there is no acceptable conversion)
Compiler: MS Visual C++ 2015
PS: Please tell me if the solution makes the code ugly or not.
Every class declares an operator=
. If you don't do it explicitly, the operator is declared implicitly. That (possibly implicit) declaration hides the base member. To unhide it, you need to use a using
declaration:
template <typename T>
struct Child : Base<T>
{
using Base<T>::operator=;
};