Created
July 10, 2024 14:24
-
-
Save flomnes/f85f7b279ec3b6330eed4176357d1d16 to your computer and use it in GitHub Desktop.
Using a std::set with a custom comparator + typeid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
class Poly | |
{ | |
public: | |
virtual std::string name() const = 0; | |
virtual ~Poly() = default; | |
}; | |
class Impl1 : public Poly | |
{ | |
public: | |
std::string name() const override | |
{ | |
return "I am Impl1"; | |
} | |
}; | |
class Impl2 : public Poly | |
{ | |
public: | |
std::string name() const override | |
{ | |
return "I am Impl2"; | |
} | |
}; | |
struct Cmp | |
{ | |
bool operator()(const Poly* p1, const Poly* p2) const | |
{ | |
return typeid(*p1).name() < typeid(*p2).name(); | |
} | |
}; | |
#include <set> | |
int main() { | |
std::set<Poly*, Cmp> s1; | |
s1.insert(new Impl1()); | |
s1.insert(new Impl2()); | |
s1.insert(new Impl2()); // (note : memory leak here) | |
for (Poly* p : s1) | |
{ | |
std::cout << p->name() << std::endl; | |
delete p; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment