Это работает в C++20, потому что эта структура имеет aggregate type, для которого в определение static_cast
ввели дополнительный пункт.
[expr.static.cast]/4:
An expression E can be explicitly converted to a type T if there is an
implicit conversion sequence
([over.best.ics])
from E to T, if overload resolution for a direct-initialization
([dcl.init]) of
an object or reference of type T from E would find at least one viable
function
([over.match.viable]),
or if T is an aggregate type
([dcl.init.aggr])
having a first element x and there is an implicit conversion sequence
from E to the type of x. ...
В С++17 этого пункта нет.
[expr.static.cast]/4:
An expression e can be explicitly converted to a type T if there is an
implicit conversion sequence from e to T, or if overload resolution for a direct-initialization of an object or reference of type T from
e would find at least one viable function
([over.match.viable]).
...
Вместо этого пытаемся неявно привести 42
к A
, что невозможно, т.к. нет соответствующего оператора/конструктора. Тогда пытаемся выполнить direct-initialization вида A(42)
. Однако в определении direct-initialization в С++17 отсутствует следующий пункт из С++20, который позволяет это сделать.
[dcl.init]/17.6.2.2:
Otherwise, if the initialization is direct-initialization, or if it is
copy-initialization where the cv-unqualified version of the source
type is the same class as, or a derived class of, the class of the
destination, constructors are considered. The applicable constructors
are enumerated
([over.match.ctor]),
and the best one is chosen through overload resolution
([over.match]).
Then:
- ...
- Otherwise, if no constructor is viable, the destination type is an aggregate class, and the initializer is a parenthesized
expression-list, the object is initialized as follows. ...
- ...
Почему в C++20 второй элемент структуры равен 0
, а не чему-либо другому (например, indeterminate value)? Это следует из следующих пунктов.
[expr.static.cast]/4:
... Otherwise, the result object is direct-initialized from E. ...
[dcl.init]/17.6.2.2:
... Let e1, …, en be the elements of the
aggregate
([dcl.init.aggr]).
Let x1, …, xk be the elements of the
expression-list. If k is greater than n, the program is ill-formed. The element ei is copy-initialized with xi for 1
≤ i ≤ k. The remaining elements are initialized with their default
member initializers, if any, and otherwise are value-initialized.
...
[dcl.init]/8.3:
To value-initialize an object of type T means:
- ...
- otherwise, the object is zero-initialized.
[dcl.init]/6.1:
To zero-initialize an object or reference of type T means:
- if T is a scalar type, the object is initialized to the value obtained by converting the integer literal
0
(zero) to T;
- ...
A
return A{42}.y;