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 : public std::enable_shared_from_this { 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.
std::shared_from_this, then you have to derive your class fromstd::enable_shared_from_this.