The last line of this code fails to compile with castingAndTernary.cpp:15: error: conditional expression between distinct pointer types ‘D1*’ and ‘D2*’ lacks a cast
A really smart compiler could have no difficulty because both can be safely casted to B* (the base class). I’m reluctant to use static_cast and dynamic_cast and so on – I’m worried that I’ll mix up the classes someday and get undefined behaviour. That’s why I created the up_cast template. This template does the bare minimum in allowed conversion. Is there a simpler way? There are other workarounds, but I can’t help but think that there’s something even simpler and safer that I could use?
struct B{ };
struct D1 : public B{ };
struct D2 : public B{ };
template<typename T,typename V>
T up_cast(V x) {
return x;
}
int main() {
bool boolean_expression = true;
B * b;
b = new D1;
b = new D2;
b = boolean_expression ? up_cast<B*>(new D1) : up_cast<B*>(new D2);
b = boolean_expression ? new D1 : new D2;
}
g++ (Ubuntu 4.3.3-5ubuntu4) 4.3.3
Update changed name from implicit_cast to up_cast as per @Konrad’s answer
Irrelevant. The standard mandates this behaviour. A really smart compiler behaves as observed.
The use of your custom cast is actually fine (and your reluctance for using an explicit cast is well-placed). However, I’d use a different name:
upcast– since that’s happening here: a cast upwards in the inheritance hierarchy.