Why can C++ ternary operator return type not be a base class type?

Viewed 81

If I get it correctly, the ternary operator has a return type. The return type is deduced from the second and third argument types of the ternary operator. If I write a ternary operator without using its result (L2 below), there is no other information to deduce the return type. So, if we want to have a single way to deduce the return type, we cannot rely on, for instance, the type of the variable in which we put the value returned by the ternary operator (L1 below).

But, instead of trying to convert types to each other, which may not be possible, why not introduce the base class use case in the standard?

That is, if there is a common base class to arguments 2 and 3, use it as the return type for the ternary operator (in a compatible way to other existing rules) for reference/pointer types. It would allow a one-line const reference/pointer initialization (like L3 below, but with no cast).

I guess there is a good reason to not do so.

class A {};
class B : public A {};
class C : public A {};

int main()
{
  B* b = new B;
  C* c = new C;
  A * a1 = true ? b : c; // L1 does not compile
  true ? b : c; // L2 does not compile
  const A * a2 = false ? static_cast<A*>(b) : static_cast<A*>(c); // L3 does compile
}

EDIT: Corrected example to reflect that the question is not related to slicing.

EDIT: To be clear, I am not asking why the code does not compile. Tons of questions exist asking why. I am asking why the C++ standard does not implement a rule to make L1 compile.

0 Answers
Related