I inherited a piece of code which is doing something like this below. What's the cleanest way to refactor this without using dynamic_cast
to check the that type are the same ?
I could mark each children type with an enum value but surely there must be something better than this ?
// Example program
#include <iostream>
#include <string>
#include <set>
class A
{
public:
virtual ~A() {}
virtual std::string GetField() const = 0;
};
class B: public A
{
public:
B(const std::string& i): m_field(i) {}
virtual std::string GetField() const { return m_field; }
std::string m_field;
};
class C: public A
{
public:
C(const std::string& i): m_field(i) {}
virtual std::string GetField() const { return m_field; }
std::string m_field;
};
class LessCmp: public std::binary_function<A*, A*, bool>
{
public:
bool operator()(A* a1, A* a2) const {
B* b1 = dynamic_cast<B*>(a1);
B* b2 = dynamic_cast<B*>(a2);
if( b1 && b2 )
return b1->GetField() < b2->GetField();
C* c1 = dynamic_cast<C*>(a1);
C* c2 = dynamic_cast<C*>(a2);
if( c1 && c2 )
return c1->GetField() < c2->GetField();
return true;
}
};
int main()
{
std::set<A*, LessCmp> myset;
myset.insert(new B("TOTO"));
myset.insert(new B("TITI"));
myset.insert(new B("TOTO"));
std::cout << myset.size() << "!\n";
myset.insert(new C("TOTO"));
std::cout << myset.size() << "!\n";
}
// this outputs 2 then 3
// it basically checks the GetField() order only when the types are identical