When you're working with a polymorphic class and find yourself needing to cast to the derived type, this is often a clue that something is wrong with the design. After all, why have virtual
functions if you still need to get to the derived class? I'm not saying there are no exceptions to this -- but I will say they are few and far between.
In this case, you (think you) need to cast in order to clone the object. Instead, I'd provide a clone
method on the base class (here called getNext
). Make that virtual
, override it in the derived class, and call that instead:
struct base {
public:
virtual std::shared_ptr<base> getNext(int x) = 0;
};
template <typename D>
struct derived : public base
{
public:
std::shared_ptr<base> getNext(int x)
{
std::shared_ptr <derived> clone = std::make_shared <derived<d>> (x, *this);
return std::static_pointer_cast <base> (clone);
}
};