1

This example:

struct X {};
struct Y : X {};

using CY = const Y;

true ? X() : CY(); // error

Which is explained in this answer, could be changed like this:

struct X { operator int() { return 0; } };
struct Y : X { operator int() const { return 0; } };

using CY = const Y;

true ? X() : CY(); // compiles, and ?: expression yields prvalue of int

The problem is according to the standard and linked explanation, which is based on interpretation of the standard, at clause [expr.cond] p4.3.2, which says:

otherwise, if T2 is a base class of T1, the target type is cv1 T2, where cv1 denotes the cv-qualifiers of T1;

CY() operand should be converted to type const X, which means that at clause [expr.cond] p6:

Otherwise, the result is a prvalue. If the second and third operands do not have the same type, and either has (possibly cv-qualified) class type, overload resolution is used to determine the conversions (if any) to be applied to the operands ([over.match.oper], [over.built]). If the overload resolution fails, the program is ill-formed. Otherwise, the conversions thus determined are applied, and the converted operands are used in place of the original operands for the remainder of this subclause.

already converted operand of type const X somehow calling Y::operator int() const, and it shouldn't, you can say, because of slicing. Right?

Also modified example compiles on all major compilers.

5
  • // error Which error? The error in the shown code persists because the operator as shown cannot be used outside a function. Commented Feb 10 at 15:54
  • [expr.cond] p4.3.2 does not apply here since T2 (const Y) is not a base class of T1 (X). Commented Feb 10 at 16:26
  • That means you need to looks at eel.is/c++draft/expr.cond#6. Both operands call their operator int and since both are now int then everything works. Commented Feb 10 at 16:27
  • @3CxEZiVlQ, you can define classes inside functions, so it is assumed that this example inside some function, int main() for example. Commented Feb 10 at 18:18
  • @NathanOliver, when T2 is const Y your reasoning is correct, but "vice versa" part from the standard is important here. So when T2 is X and the target type is cv1 T2, which is const X, p4.3.2 applies. Check linked answer for more details. Commented Feb 10 at 18:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.