Yves Calaci
Yves Calaci

Reputation: 1129

Check whether the current underlying type of a std::shared_ptr<> is T

I have a shared pointer storing a base class, like this:

std::shared_ptr<Base> baseClassPointer;

How do I check whether it is currently holding an instance of an SuperClassA? Where:

public class SuperClassA : public Base {} // There can be many other superclasses

I've tried something like below, but obviously did not work:

std::is_same<SuperClassA, decltype(baseClassPointer->get())>::value;

Upvotes: 3

Views: 2078

Answers (1)

Yves Calaci
Yves Calaci

Reputation: 1129

For those interested on knowing how I did this, here goes:

bool same = typeid(SuperClassA) == typeid(*baseClassPointer->get());

Or:

bool same = std::dynamic_pointer_cast<SuperClassA>(baseClassPointer).use_count() > 0;

Or even better (performance-wise):

bool same = dynamic_cast<SuperClassA*>(baseClassPointer->get()) != nullptr;

Upvotes: 1

Related Questions