Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use the ternary operator here?

This line won't compile:

Shape shape = (i % 2) ? Circle(5) : Rectangle(5, 5);

(I know it's useless since whatever the expression returns will be reduced to a simple Shape, that's not the point).

Can't figure out why it won't compile. I'm creating a Shape variable named shape (which I think at this point creates a new Shape), and then I'm assigning this variable the result of an expression. Why doesn't this compile?

The error:

no match for ternary operator

What's really weird is that the longer code with exact same meaning does compile and run as expected:

    Shape shape;
    if (i % 2)
        shape = Rectangle(5, 5);
    else
        shape = Circle(5);
like image 597
Aviv Cohn Avatar asked Oct 03 '14 23:10

Aviv Cohn


1 Answers

The detailed conversion rules for the conditional operator are rather complex (you can find the full quote from the standard in this answer if you are interested). The short of it is that, when used with objects of class type, it will attempt to convert its second operand to match the type of the third, and its third operand to match the type of the second, but it won't try to convert both to a third class type.

Since Circle isn't convertible to Rectangle and Rectangle isn't convertible to Circle, the compiler will complain (well, unless the two types define some odd conversion to pointer, scoped enumeration or arithmetic types, in which case §5.16 [expr.cond]/p5 comes into play).

Note also that your assignment will slice the object, which probably isn't a good idea.

like image 120
T.C. Avatar answered Sep 28 '22 05:09

T.C.