This question already has an answer here:
I have some software that implements a graph as an adjacency list. I have an algorithm that I am attempting to make generic. I want users to be able to implement their own version of Vertex to be used in the algorithm.
As new vertices arrive in the driver, I want to test if the graph contains that vertex already. I am using std::find on the Base class Vertex in the algorithm to do this, which uses operator== to test if two elements are the same. Since the Vertex class doesn't actually contain data, it has no way of determining if two Vertexs are equal. Therefore, I want to force users who use my classes to overload their own operator== on their Vertex class.
class Vertex {
virtual bool operator==(const Vertex& other) = 0;
}
class MyVertex : public Vertex {
bool operator==(const MyVertex& other);
}
When I compile this I get an error "invalid new-expression of abstract class type MyVertex because operator== is pure within MyVertex". I understand that this has to do with how c++ matches the signatures of the functions. And these don't match since the parameters are of different types, even though MyVertex is derived from Vertex.
Michael Kristofik asked a similar question here, but there was no accepted answer and the given answers didn't seem to help. I tried dynamic casting in my derived Vertex but then I got seg faults in my algorithm due to std::find not working properly due to the operator== not performing as expected.
My question is: What is the proper way to ensure users overload a pure virtual operator== function in a derived class? and what is the proper way to implement that overloading?
I am using c++11
Aucun commentaire:
Enregistrer un commentaire