I have the following hierarchy:
class base
{
public:
virtual ~base(){}
virtual void foo() {}
};
template
class derived1 : public base
{
Move the logic which depends on the type into the type.
Instead of:
if (dynamic_cast*>(b) ||
dynamic_cast*>(b) ||
dynamic_cast*>(b))
std::cout << "is derived1";
else if (dynamic_cast*>(b) ||
dynamic_cast*>(b) ||
dynamic_cast*>(b))
std::cout << "is derived2";
add a virtual print_name() const
function to base
, and then do:
void example() {
std::unique_ptr b(new derived1());
b->print_name();
}
class base
{
public:
~base(){}
virtual void foo() {}
virtual void print_name() const = 0;
};
template
class derived1 : public base
{
virtual void foo() {}
virtual void print_name() const {
std::cout << "is derived1";
}
};
template
class derived2 : public base
{
virtual void foo() {}
virtual void print_name() const {
std::cout << "is derived2";
}
};