I made 'Derived' class which is deriving 'Base' class. It is using CRTP. Base class contains one unary and one binary operator. Derived class is implementing those virtual operator functions.
template <typename T> class Base
{
public:
virtual bool operator==(T operand) = 0;
virtual bool operator!() = 0;
};
class Derived : public Base<Derived>
{
public:
virtual bool operator==(Derived operand){ return true; }
virtual bool operator!(){ return false; }
};
Template function notf and equalf are made for testing Derived class's member operators. Function notf is taking one Base by reference, and calls its ! operator. Function equalf does similar thing.
template <typename T> bool notf(Base<T>& x)
{
return !x;
}
template <typename T> bool equalf(Base<T>& x, Base<T>& y)
{
return x == y;
}
And the main function calls those template functions.
int main()
{
Derived x, y;
cout << notf(x);
cout << equalf(x, y);
return 0;
}
And C2678 error is generated on equalf function. The compiler says, error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Base<Derived>' (or there is no acceptable conversion)
. But I don't know what is problem because notf function is working well. When the code compiled except equalf function, it works well.
When I made equalf function to show the type of parameters, it shows "class Derived" and "class Derived". If it's true, then why the error message says left-hand operand of type 'Base<Derived>'
?
Base<T>::operator==(T operand)
can't take a Base<T>
argument (since there's no conversion defined).
It's difficult to suggest a fix, because the code points in many possible design directions.
However, anyway, the idea of virtual comparison operator, or virtual assignment, is generally ungood, because it moves type checking to run time, so that you need much more testing, and more intricate code.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments