I'm trying to implement generic wrapper in C++ that will be able to compare two things. I've done it as follows:
template <class T>
class GameNode {
public:
//constructor
GameNode( T value )
: myValue( value )
{ }
//return this node's value
T getValue() {
return myValue;
}
//ABSTRACT
//overload greater than operator for comparison of GameNodes
virtual bool operator>( const GameNode<T> other ) = 0;
//ABSTRACT
//overload less than operator for comparison of GameNodes
virtual bool operator<( const GameNode<T> other ) = 0;
private:
//value to hold in this node
T myValue;
};
It would seem to be I can't overload the '<' and '>' operators in this way, so I'm wondering what I can do to get around this.
Your operator functions are accepting their arguments by copy. However, a new instance of GameNode can not be constructed because of the pure virtual functions. You probably want to accept those arguments by reference instead.
Abstract types are only useful because they are polymorphic, and in fact they MUST be used polymorphically (this is the difference between virtual and pure virtual aka abstract).
Polymorphism requires a reference or pointer. You want a reference in this case.
Passing by value tries to create a new object by copying the argument, but creating an instance of an abstract type isn't possible. Passing by reference uses the existing instance instead of creating a new one, and avoids this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With