@@ -1504,13 +1504,38 @@ $(H4 $(LNAME2 cast_floating, Floating Point))
1504
1504
1505
1505
$(H4 $(LNAME2 cast_struct, Structs))
1506
1506
1507
- $(P Casting an expression $(I e) to a struct $(I S), when the
1508
- expression is not a struct of the same type, is equivalent to a
1509
- $(GLINK PostfixExpression):)
1507
+ $(P An expression `e` can be cast to a struct type `S`:)
1510
1508
1509
+ * The compiler attempts a
1510
+ $(RELATIVE_LINK2 type-constructor-arguments, *PostfixExpression*) `S(e)`.
1511
+ If that would fail:
1512
+ * When `e` is a struct or static array instance, its data is reinterpreted as
1513
+ the target type `S`. The data sizes must match.
1514
+ * Otherwise, it is an error.
1515
+
1516
+ $(SPEC_RUNNABLE_EXAMPLE_RUN
1511
1517
---
1512
- S(e)
1518
+ struct S
1519
+ {
1520
+ int i;
1521
+ }
1522
+ struct R
1523
+ {
1524
+ short[2] a;
1525
+ }
1526
+
1527
+ S s = cast(S) 5; // same as S(5)
1528
+ assert(s.i == 5);
1529
+ static assert(!__traits(compiles, cast(S) long.max)); // S(long.max) is invalid
1530
+
1531
+ R r = R([1, 2]);
1532
+ s = cast(S) r; // reinterpret r
1533
+ assert(s.i == 0x00020001);
1534
+
1535
+ byte[4] a = [1, 0, 2, 0];
1536
+ assert(r == cast(R) a); // reinterpret a
1513
1537
---
1538
+ )
1514
1539
1515
1540
$(P A struct instance can be cast to a static array type when
1516
1541
their `.sizeof` properties each give the same result.)
@@ -1520,7 +1545,7 @@ $(H4 $(LNAME2 cast_struct, Structs))
1520
1545
struct S { short a, b, c; }
1521
1546
1522
1547
S s = S(1, 2, 3);
1523
- static assert(!__traits(compiles, cast(short[2]) s));
1548
+ static assert(!__traits(compiles, cast(short[2]) s)); // size mismatch
1524
1549
1525
1550
short[3] x = cast(short[3]) s;
1526
1551
assert(x.tupleof == s.tupleof);
@@ -1730,6 +1755,7 @@ $(H4 $(LNAME2 type-constructor-arguments, Constructing a Type with an Argument L
1730
1755
$(P A type can precede a list of arguments. See:)
1731
1756
1732
1757
* $(DDSUBLINK spec/struct, struct-literal, Struct Literals)
1758
+ * $(DDSUBLINK spec/struct, struct-constructor, Struct Constructors)
1733
1759
* $(RELATIVE_LINK2 uniform_construction_syntax, Uniform construction syntax for built-in scalar types)
1734
1760
1735
1761
$(H3 $(LEGACY_LNAME2 index_operations, index_expressions, Index Operations))
0 commit comments