This code compiles. Its obviously wrong because B can never be a WTF. Is there a way i can write the typecast so this is a compile time error?
class B{ public: virtual void abc(){} };
class D1 : public B{};
class WTF{ };
template<class T, class TT>
T DoSomething(TT o){
return dynamic_cast<T>(o);
}
B*Factory() { return new D1; }
int main(){
DoSomething<D1*, B*>(Factory());
DoSomething<WTF*, B*>(Factory());
}
There are two solutions to this problem, depending on what you want the code to be doing.
The first solution: Change the
dynamic_castintostatic_cast. This solution assumes that you never use classWTFin 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
WTFcreated sometime in the future will inherit from classBor not.The above source code can also be found here. Its output looks like this:
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.