vendredi 4 décembre 2015

How to identify class type to cast a shared_ptr to that type

I have a class hierarchy and I want get shared from this and cast it to the specific class type. So I want this:

class A
{
    std::shared_ptr<A> getSharedFromThis()
    {
        return std::static_pointer_cast<A>(shared_from_this());
    }
};

class B : public A
{
    std::shared_ptr<B> getSharedFromThis()
    {
        return std::static_pointer_cast<B>(shared_from_this());
    }
};

In superclass I can write a templated variant but it is still not cool:

template <typename T>
std::shared_ptr<T> getSharedFromThis()
{
    return std::static_pointer_cast<T>(shared_from_this());
}

How can I make it generic so that it will understand that it is in class B and cast to B the shared_ptr and now write the same logic in 100 classes that are in the same hierarchy.

Aucun commentaire:

Enregistrer un commentaire