4
votes

Paragraph 4 of [expr.cast] (in the latest draft of the C++ standard available at the time of writing) which describes the behaviour of a C-style cast says the following:

The conversions performed by

  • a const_­cast,
  • a static_­cast,
  • a static_­cast followed by a const_­cast,
  • a reinterpret_­cast, or
  • a reinterpret_­cast followed by a const_­cast,

can be performed using the cast notation of explicit type conversion. The same semantic restrictions and behaviors apply, with the exception that in performing a static_­cast in the following situations the conversion is valid even if the base class is inaccessible:

  • a pointer to an object of derived class type or an lvalue or rvalue of derived class type may be explicitly converted to a pointer or reference to an unambiguous base class type, respectively;
  • a pointer to member of derived class type may be explicitly converted to a pointer to member of an unambiguous non-virtual base class type;
  • a pointer to an object of an unambiguous non-virtual base class type, a glvalue of an unambiguous non-virtual base class type, or a pointer to member of an unambiguous non-virtual base class type may be explicitly converted to a pointer, a reference, or a pointer to member of a derived class type, respectively.

If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed. If a conversion can be interpreted in more than one way as a static_­cast followed by a const_­cast, the conversion is ill-formed. [...]

My question is how can "a conversion be interpreted in more than one way as a static_cast followed by a const_cast"?

Thank you.

1
Ok, but the first sentence says: "[...] the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed". Using static_cast to cast to an ambiguous base class is ill-formed, so the highlighted sentence is not necessary anymore. Also, the highlighted sentence singles out a more specific case: "a static_­cast followed by a const_­cast". - user42768
Something like this: a class with two user-defined conversion operators, one to int const ** and another to int* const *. The C-style cast is to int** Demo - Igor Tandetnik

1 Answers

4
votes

Something like this:

struct S {
    operator int const**() { return nullptr; }
    operator int *const*() { return nullptr; }
};

S s;
(int**)s;  // error: cannot cast from type 'S' to pointer type 'int **'

Similar casts to int const** and int *const* succeed. Demo