I have polymorphic classes Base, Derived1 and Derived2.
I want to make
bool b = typeid(*base) == typeid(Derived1);
dynamic_cast<typename std::conditional<b, Derived1*, Derived2*>::type>(base)
My compiler says that b is not a compile time expression (and I understand what this means). Is there a way to solve the problem?
You do not need
std::conditionalhere. As you are making a dynamic cast, this cast happens at runtime anyhow, so theres no point in trying to push it into compile time. Just removestd::conditionaland the problem is gone:Note that this code is as pseudo as yours and that chances are high that you do not need a cast in the first place. Maybe you do, but without context I guess that you rather need a virtual function.
Moreover,
bool b = typeid(*base) == typeid(Derived1);looks like you want to cast toDerived1*only when the cast would suceed. However,dynamic_castdoes already tell you when a cast cannot be made by returning anullptr.If you are looking for a way to "hide" the cast in a function, this isnt going to work. If you write a
base* my_cast(auto* x)as you mention in a comment, it will always return abase*no matter what you cast inside the function:Output is: