I'm stuck trying to cast FROM a shared_ptr<void>
. I know it is a shared_ptr<A>
or a shared_ptr<B>
, but I can not find how to check which one it is.
A and B are 2 different not related classes.
I would like to do something like:
//x.valuePtr is a shared_ptr<void>
if(x.valuePtr is shared_ptr<A>){
... do things with the pointer to an A object
} else if (x.valuePtr is shared_ptr<B>){
... do things with the pointer to an B object
}
I have a property (of a class I can not change) which is of type shared_ptr<void>
.
In most cases I know which is the real type of that pointer so I can use static_pointer_cast
without problems. For example:
// If I know x.valuePtr is shared_ptr<A>
x.valuePtr = std::make_shared<A>();
// I can use static_pointer_cast somewhere else in the application and it works fine
std::shared_ptr<A> a_ptr = std::static_pointer_cast<A> (x.valuePtr);
// Same happens when I know it is a shared_ptr<B>
x.valuePtr = std::make_shared<B>();
std::shared_ptr<B> b_ptr = std::static_pointer_cast<B> (x.valuePtr);
But now I have a problem because it can be either of them (a shared_ptr<A>
or a shared_ptr<B>
). If I use static_pointer_cast<A>
(or <B>
), that line compiles and throws no exception, but it does throw an exception as soon as I try to use something specific from the casted ptr if it was the wrong type. For example:
// If x.valuePtr is shared_ptr<A>
x.valuePtr = std::make_shared<A>();
// But if I try to cast it to shared_ptr<B> somewhere in the application where it could be shared_ptr<A> or shared_ptr<B>
std::shared_ptr<B> b_ptr = std::static_pointer_cast<B> (x.valuePtr); // this does no fail
// It throws an exception when I try to use b_ptr. For example
b_ptr->AMethodInB();
I tried doing different checks after the static_pointer_cast
(for null, empty shared_ptr
, etc) but nothing seems to work:
x.valuePtr = std::make_shared<A>();
std::shared_ptr<B> b_ptr = std::static_pointer_cast<B> (x.valuePtr);
if(b_ptr == NULL || b_ptr.get() == NULL || !b_ptr){
"It never gets into this line"
"I would be able to try to cast it to shared_ptr<A>"
}
b_ptr->AMethodInB(); // and keeps failing here
I also tried using the dynamic_pointer_cast<B>
, but does no compile ("error: cannot dynamic_cast .... (source is not a pointer to class)
"). Also I found it is not possible to dynamic_cast
FROM void
here
Is there any way I can do to check if the static_pointer_cast
actually worked fine?
Or to check somehow the real type of this shared_ptr<void>
?
PD: I'm using c++11, gcc 4.8.2.