Lets say I have an abstract base class and a derived class with some unique functionality:
class Shape
{
public:
Shape();
};
class Circle : public Shape
{
public:
Circle(int radius) : radius(radius);
int getRadius() { return this->radius; };
private:
int radius;
};
Now I can put Circle*:s in std::vector and check afterwards if vector has Shape*
std::vector< Circle* > v;
Circle* circle = new Circle(1);
v.push_back(circle);
// ...
Shape* someShape = ...; // I know it's a Circle but the pointer comes from class that only knows about Shapes
for(std::vector< Circle* >::iterator it = v.begin(); it != v.end(); ++it)
{
Circle* c = *it;
if((Shape)c == someShape)
{
// found
}
}
// ...
delete c;
But I want to use std::unordered_set (applies also to std::unordered_map, std::set, std::map) because it has faster-than-linear find() and count()
std::unordered_set< Circle* > u;
Circle* circle = new Circle(1);
u.insert(circle);
// ...
Shape* someShape = ...; // I know it's a Circle but the pointer comes from class that only knows about Shapes
if(u.count(someShape) == 1)
{
// found
}
Instead of the obivious I get “undefined function” as there only exists std::unordered_set< Key >::count(Key& k);
Is there any way I can find() or count() from std::unordered_set using base class?
If you know it’s a circle then you can simply cast
someShapetoCircle *and pass that tofind().