There are two solutions to this problem, depending on what you want the code to be doing.
The first solution: Change the dynamic_cast
into static_cast
. This solution assumes that you never use class WTF
in a class hierarchy with multiple inheritance. See below.
The second solution: You realize that C++ allows multiple inheritance. There is no way for you nor for the compiler to predict whether an arbitrary instance of WTF
created sometime in the future will inherit from class B
or not.
#include <stdio.h>
class B{ public: virtual void abc(){} };
class D1 : public B{};
class WTF{ };
class WTF_B : public WTF, public B {};
template<class T, class TT>
T DoSomething(TT o){
return dynamic_cast<T>(o);
}
B*Factory1() { return new D1; }
B*Factory2() { return new WTF_B; }
int main(){
printf("%p\n", DoSomething<D1*, B*>(Factory1()));
printf("%p\n", DoSomething<WTF*, B*>(Factory1()));
printf("%p\n", DoSomething<WTF*, B*>(Factory2()));
return 0;
}
The above source code can also be found here. Its output looks like this:
0x861a008
(nil)
0x861a028
In either case, the choice between solution 1 and solution 2 is yours - but the choice is yours only if you know what you are doing.