-
-
Notifications
You must be signed in to change notification settings - Fork 369
/
type.dd
882 lines (710 loc) · 26.6 KB
/
type.dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
Ddoc
$(SPEC_S Types,
$(HEADERNAV_TOC)
$(H2 $(LNAME2 grammar, Grammar))
$(P D is statically typed. Every expression has a type. Types constrain the values
an expression can hold, and determine the semantics of operations on those values.
)
$(GRAMMAR
$(GNAME Type):
$(GLINK TypeCtors)$(OPT) $(GLINK BasicType) $(GLINK TypeSuffixes)$(OPT)
$(GNAME TypeCtors):
$(GLINK TypeCtor)
$(GLINK TypeCtor) $(GSELF TypeCtors)
$(GNAME TypeCtor):
$(D const)
$(D immutable)
$(D inout)
$(D shared)
$(GNAME BasicType):
$(GLINK FundamentalType)
$(D .) $(GLINK QualifiedIdentifier)
$(GLINK QualifiedIdentifier)
$(GLINK Typeof)
$(GLINK Typeof) $(D .) $(GLINK QualifiedIdentifier)
$(GLINK TypeCtor) $(D $(LPAREN)) $(GLINK Type) $(D $(RPAREN))
$(GLINK Vector)
$(GLINK2 traits, TraitsExpression)
$(GLINK MixinType)
$(GNAME Vector):
$(D __vector) $(D $(LPAREN)) $(GLINK VectorBaseType) $(D $(RPAREN))
$(GNAME VectorBaseType):
$(GLINK Type)
$(GNAME FundamentalType):
$(MULTICOLS 5,
$(D bool)
$(D byte)
$(D ubyte)
$(D short)
$(D ushort)
$(D int)
$(D uint)
$(D long)
$(D ulong)
$(D cent)
$(D ucent)
$(D char)
$(D wchar)
$(D dchar)
$(D float)
$(D double)
$(D real)
$(D ifloat)
$(D idouble)
$(D ireal)
$(D cfloat)
$(D cdouble)
$(D creal)
$(D void))
$(GNAME TypeSuffixes):
$(GLINK TypeSuffix) $(GSELF TypeSuffixes)$(OPT)
$(GNAME TypeSuffix):
$(D *)
$(D [ ])
$(D [) $(GLINK2 expression, AssignExpression) $(D ])
$(D [) $(GLINK2 expression, AssignExpression) $(D ..) $(GLINK2 expression, AssignExpression) $(D ])
$(D [) $(GLINK Type) $(D ])
$(D delegate) $(GLINK2 function, Parameters) $(GLINK2 function, MemberFunctionAttributes)$(OPT)
$(D function) $(GLINK2 function, Parameters) $(GLINK2 function, FunctionAttributes)$(OPT)
$(GNAME QualifiedIdentifier):
$(GLINK_LEX Identifier)
$(GLINK_LEX Identifier) $(D .) $(GSELF QualifiedIdentifier)
$(GLINK2 template, TemplateInstance)
$(GLINK2 template, TemplateInstance) $(D .) $(GSELF QualifiedIdentifier)
$(GLINK_LEX Identifier) $(D [) $(GLINK2 expression, AssignExpression) $(D])
$(GLINK_LEX Identifier) $(D [) $(GLINK2 expression, AssignExpression) $(D] .) $(GSELF QualifiedIdentifier)
)
* $(RELATIVE_LINK2 basic-data-types, Basic Data Types) are leaf types.
* $(RELATIVE_LINK2 derived-data-types, Derived Data Types) build on leaf types.
* $(RELATIVE_LINK2 user-defined-types, User-Defined Types) are aggregates of basic and derived types.
$(H2 $(LEGACY_LNAME2 Basic Data Types, basic-data-types, Basic Data Types))
$(TABLE_3COLS Basic Data Types,
$(THEAD Keyword, Default Initializer ($(D .init)), Description)
$(TROW $(D void), no default initializer, `void` has no value)
$(TROW $(RELATIVE_LINK2 bool, $(D bool)), $(D false), boolean value)
$(TROW $(D byte), $(D 0), signed 8 bits)
$(TROW $(D ubyte), $(D 0u), unsigned 8 bits)
$(TROW $(D short), $(D 0), signed 16 bits)
$(TROW $(D ushort), $(D 0u), unsigned 16 bits)
$(TROW $(D int), $(D 0), signed 32 bits)
$(TROW $(D uint), $(D 0u), unsigned 32 bits)
$(TROW $(D long), $(D 0L), signed 64 bits)
$(TROW $(D ulong), $(D 0uL), unsigned 64 bits)
$(TROW $(GDEPRECATED $(D cent)), $(D 0), signed 128 bits)
$(TROW $(GDEPRECATED $(D ucent)), $(D 0u), unsigned 128 bits)
$(TROW $(D float), $(D float.nan), 32 bit floating point)
$(TROW $(D double), $(D double.nan), 64 bit floating point)
$(TROW $(D real), $(D real.nan), largest floating point size available)
$(TROW $(D ifloat), $(D float.nan*1.0i), imaginary float)
$(TROW $(D idouble), $(D double.nan*1.0i), imaginary double)
$(TROW $(D ireal), $(D real.nan*1.0i), imaginary real)
$(TROW $(D cfloat), $(D float.nan+float.nan*1.0i), a complex number of two float values)
$(TROW $(D cdouble), $(D double.nan+double.nan*1.0i), complex double)
$(TROW $(D creal), $(D real.nan+real.nan*1.0i), complex real)
$(TROW $(D char), $(D '\xFF'), unsigned 8 bit (UTF-8 code unit))
$(TROW $(D wchar), $(D '\uFFFF'), unsigned 16 bit (UTF-16 code unit))
$(TROW $(D dchar), $(D '\U0000FFFF'), unsigned 32 bit (UTF-32 code unit))
)
$(P Endianness of basic types is part of the $(DDSUBLINK spec/abi, endianness, ABI))
$(IMPLEMENTATION_DEFINED The real floating point type has at least the range and precision
of the `double` type. On x86 CPUs it is often implemented as the 80 bit Extended Real
type supported by the x86 FPU.
)
$(NOTE 128-bit integer types `cent` and `ucent`
$(DDSUBLINK deprecate, 128-bit integer types, have been deprecated).)
$(P NOTE: Complex and imaginary types `ifloat`, `idouble`, `ireal`, `cfloat`, `cdouble`,
and `creal` have been deprecated in favor of `std.complex.Complex`.)
$(H2 $(LEGACY_LNAME2 Derived Data Types, derived-data-types, Derived Data Types))
$(UL
$(LI Pointers)
$(LI $(DDSUBLINK spec/arrays, static-arrays, Static Arrays))
$(LI $(DDSUBLINK spec/arrays, dynamic-arrays, Dynamic Arrays))
$(LI $(DDLINK spec/hash-map, Associative Array, Associative Arrays))
$(LI $(RELATIVE_LINK2 functions, Function Types))
$(LI $(RELATIVE_LINK2 delegates, Delegate Types))
$(LI $(DDSUBLINK spec/template, homogeneous_sequences, Type Sequences))
)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
int* p; // pointer
int[2] sa; // static array
int[] da; // dynamic array/slice
int[string] aa; // associative array
void function() fp; // function pointer
import std.meta : AliasSeq;
AliasSeq!(int, string) tsi; // type sequence instance
---
)
$(H3 $(LNAME2 pointers, Pointers))
$(P A pointer to type $(D T) has a value which is a reference (address) to another
object of type $(D T). It is commonly called a $(I pointer to T) and its type is
`T*`. To access the object value, use the `*` dereference operator:
)
$(SPEC_RUNNABLE_EXAMPLE_RUN
---------
int* p;
assert(p == null);
p = new int(5);
assert(p != null);
assert(*p == 5);
(*p)++;
assert(*p == 6);
---------
)
$(P If a pointer contains a $(I null) value, it is not pointing to a valid object.)
$(P When a pointer to $(I T) is dereferenced, it must either contain a $(I null) value,
or point to a valid object of type $(I T).)
$(IMPLEMENTATION_DEFINED
$(OL
$(LI The behavior when a $(I null) pointer is dereferenced. Typically the program
will be aborted.)
))
$(UNDEFINED_BEHAVIOR dereferencing a pointer that is not $(I null) and does not point
to a valid object of type $(I T).)
$(P To set a pointer to point at an existing object, use the
`&` *address of* operator:)
$(SPEC_RUNNABLE_EXAMPLE_RUN
---------
int i = 2;
int* p = &i;
assert(p == &i);
assert(*p == 2);
*p = 4;
assert(i == 4);
---------
)
$(P See also $(DDSUBLINK spec/expression, pointer_arithmetic, Pointer Arithmetic).)
$(H2 $(LEGACY_LNAME2 User Defined Types, user-defined-types, User-Defined Types))
$(UL
$(LI $(DDLINK spec/enum, Enums, Enums))
$(LI $(DDLINK spec/struct, Structs and Unions, Structs and Unions))
$(LI $(DDLINK spec/class, Classes, Classes))
$(LI $(DDLINK spec/interface, Interfaces, Interfaces))
)
$(H2 $(LNAME2 type-conversions, Type Conversions))
See also: $(GLINK2 expression, CastExpression).
$(H3 $(LEGACY_LNAME2 Pointer Conversions, pointer-conversions, Pointer Conversions))
$(P $(RELATIVE_LINK2 pointers, Pointers) implicitly convert to `void*`.)
$(P Casting between pointers and non-pointers is allowed. Some pointer casts
are disallowed in $(DDLINK spec/memory-safe-d, Memory-Safe-D-Spec, `@safe` code).)
$(BEST_PRACTICE do not cast any pointer to a non-pointer type that points to data
allocated by the garbage collector.
)
$(H3 $(LEGACY_LNAME2 Implicit Conversions, implicit-conversions, Implicit Conversions))
$(P Implicit conversions are used to automatically convert
types as required. The rules for integers are detailed in the next sections.
)
$(P An enum can be $(DDSUBLINK spec/enum, named_enums, implicitly converted) to its base
type, but going the other way requires an explicit
conversion.)
$(UL
$(LI All types implicitly convert to $(RELATIVE_LINK2 noreturn, `noreturn`).)
$(LI Static and dynamic arrays implicitly convert to $(DDSUBLINK spec/arrays, void_arrays, `void` arrays).)
$(LI $(DDSUBLINK spec/function, function-pointers-delegates, Function pointers and delegates)
can convert to covariant types.)
)
$(H4 $(LNAME2 class-conversions, Class Conversions))
$(P A derived class can be implicitly converted to its base class, but going
the other way requires an explicit cast. For example:)
$(SPEC_RUNNABLE_EXAMPLE_RUN
-------------------
class Base {}
class Derived : Base {}
Base bd = new Derived(); // implicit conversion
Derived db = cast(Derived)new Base(); // explicit conversion
-------------------
)
$(P A dynamic array, say `x`, of a derived class can be implicitly converted
to a dynamic array, say `y`, of a base class iff elements of `x` and `y` are
qualified as being either both `const` or both `immutable`.)
$(SPEC_RUNNABLE_EXAMPLE_RUN
-------------------
class Base {}
class Derived : Base {}
const(Base)[] ca = (const(Derived)[]).init; // `const` elements
immutable(Base)[] ia = (immutable(Derived)[]).init; // `immutable` elements
-------------------
)
$(P A static array, say `x`, of a derived class can be implicitly converted
to a static array, say `y`, of a base class iff elements of `x` and `y` are
qualified as being either both `const` or both `immutable` or both mutable
(neither `const` nor `immutable`).)
$(SPEC_RUNNABLE_EXAMPLE_RUN
-------------------
class Base {}
class Derived : Base {}
Base[3] ma = (Derived[3]).init; // mutable elements
const(Base)[3] ca = (const(Derived)[3]).init; // `const` elements
immutable(Base)[3] ia = (immutable(Derived)[3]).init; // `immutable` elements
-------------------
)
$(H3 $(LEGACY_LNAME2 Integer Promotions, integer-promotions, Integer Promotions))
$(P Integer Promotions are conversions of the following types:
)
$(TABLE2 Integer Promotions,
$(THEAD from, to)
$(TROW
$(ARGS $(D bool)),
$(ARGS $(D int))
)
$(TROW
$(ARGS $(D byte)),
$(ARGS $(D int))
)
$(TROW
$(ARGS $(D ubyte)),
$(ARGS $(D int))
)
$(TROW
$(ARGS $(D short)),
$(ARGS $(D int))
)
$(TROW
$(ARGS $(D ushort)),
$(ARGS $(D int))
)
$(TROW
$(ARGS $(D char)),
$(ARGS $(D int))
)
$(TROW
$(ARGS $(D wchar)),
$(ARGS $(D int))
)
$(TROW
$(ARGS $(D dchar)),
$(ARGS $(D uint))
)
)
$(P If an enum has as a base type one of the types
in the left column, it is converted to the type in the right
column.
)
$(P Integer promotion applies to each operand of a binary expression:)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
void fun()
{
byte a;
auto b = a + a;
static assert(is(typeof(b) == int));
// error: can't implicitly convert expression of type int to byte:
//byte c = a + a;
ushort d;
// error: can't implicitly convert expression of type int to ushort:
//d = d * d;
int e = d * d; // OK
static assert(is(typeof(int() * d) == int));
dchar f;
static assert(is(typeof(f - f) == uint));
}
---
)
$(RATIONALE
* 32-bit integer operations are often faster than smaller integer types
for single variables on modern architectures.
* Promotion helps avoid accidental overflow which is more common with small integer types.
)
$(H3 $(LEGACY_LNAME2 Usual Arithmetic Conversions, usual-arithmetic-conversions, Usual Arithmetic Conversions))
$(P The usual arithmetic conversions convert operands of binary
operators to a common type. The operands must already be
of arithmetic types.
The following rules are applied
in order, looking at the base type:
)
$(OL
$(LI If either operand is `real`, the other operand is
converted to `real`.)
$(LI Else if either operand is `double`, the other operand is
converted to `double`.)
$(LI Else if either operand is `float`, the other operand is
converted to `float`.)
$(LI Else the integer promotions above are done on each operand,
followed by:
$(OL
$(LI If both are the same type, no more conversions are done.)
$(LI If both are signed or both are unsigned, the
smaller type is converted to the larger.)
$(LI If the signed type is larger than the unsigned
type, the unsigned type is converted to the signed type.)
$(LI The signed type is converted to the unsigned type.)
)
)
)
$(RATIONALE The above rules follow C99, which makes porting code from C easier.)
$(P $(B Example:) Signed and unsigned conversions:)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
int i;
uint u;
static assert(is(typeof(i + u) == uint));
static assert(is(typeof(short() + u) == uint));
static assert(is(typeof(ulong() + i) == ulong));
static assert(is(typeof(long() - u) == long));
static assert(is(typeof(long() * ulong()) == ulong));
---
)
$(P $(B Example:) Floating point:)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
float f;
static assert(is(typeof(f + ulong()) == float));
double d;
static assert(is(typeof(f * d) == double));
static assert(is(typeof(real() / d) == real));
---
)
$(H4 $(LNAME2 enum-ops, Enum Operations))
$(P If one or both of the operand types is an $(DDLINK spec/enum, Enums, enum) after
undergoing the above conversions, the result type is determined as follows:)
$(OL
$(LI If the operands are the same type, the result will be of
that type.)
$(LI If one operand is an enum and the other is the base type
of that enum, the result is the base type.)
$(LI If the two operands are different enums,
the result is the closest base type common to both. A base type being closer
means there is a shorter sequence of conversions to base type to get there from the
original type.)
)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
enum E { a, b, c }
enum F { x, y }
void test()
{
E e = E.a;
e = e | E.c;
//e = e + 4; // error, can't assign int to E
int i = e + 4;
e += 4; // OK, see below
F f;
//f = e | f; // error, can't assign int to F
i = e | f;
}
---
)
$(NOTE Above, `e += 4` compiles because the
$(DDSUBLINK spec/expression, assignment_operator_expressions, operator assignment)
is equivalent to `e = cast(E)(e + 4)`.)
$(H3 $(LEGACY_LNAME2 disallowed-conversions, integer-conversions, Integer Type Conversions))
$(P An integer of type `I` implicitly converts to another integer type `J` when
`J.sizeof >= I.sizeof`.)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
void f(byte b, ubyte ub, short s)
{
b = ub; // OK, bit pattern same
ub = b; // OK, bit pattern same
s = b; // OK, widening conversion
b = s; // error, implicit narrowing
}
---
)
$(P Integer values cannot be implicitly converted to another
type that cannot represent the integer bit pattern after
$(RELATIVE_LINK2 integer-promotions, integral promotion). For example:)
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
ubyte u1 = -1; // error, -1 cannot be represented in a ubyte
ushort u2 = -1; // error, -1 cannot be represented in a ushort
uint u3 = -1; // ok, -1 can be represented in an int, which can be converted to a uint
ulong u4 = -1; // ok, -1 can be represented in a long, which can be converted to a ulong
---
)
$(H3 $(LNAME2 floating-point-conversions, Floating Point Type Conversions))
* Integral types implicitly convert to floating point types.
* Floating point types cannot be implicitly converted to integral types.
$(SPEC_RUNNABLE_EXAMPLE_FAIL
---
void f(int i, float f)
{
f = i; // OK
i = f; // error
}
---
)
* Complex or imaginary floating point types cannot be implicitly converted
to non-complex floating point types.
* Non-complex floating point types cannot be implicitly converted to imaginary floating
point types.
$(H3 $(LNAME2 vrp, Value Range Propagation))
$(P Besides type-based implicit conversions, D allows certain integer
expressions to implicitly convert to a narrower type after
integer promotion. This works by analysing the minimum and
maximum possible range of values for each expression.
If that range of values matches or is a subset of a narrower
target type's value range, implicit
conversion is allowed. If a subexpression is known at compile-time,
that can further narrow the range of values.)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
void fun(char c, int i, ubyte b)
{
// min is c.min + 100 > short.min
// max is c.max + 100 < short.max
short s = c + 100; // OK
ubyte j = i & 0x3F; // OK, 0 ... 0x3F
//ubyte k = i & 0x14A; // error, 0x14A > ubyte.max
ushort k = i & 0x14A; // OK
k = i & b; // OK, 0 ... b.max
//b = b + b; // error, b.max + b.max > b.max
s = b + b; // OK, 0 ... b.max + b.max
}
---
)
$(P Note the implementation does not track the range of possible values for
mutable variables:)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
void fun(int i)
{
ushort s = i & 0xff; // OK
// s is now assumed to be s.min ... s.max, not 0 ... 0xff
//ubyte b = s; // error
ubyte b = s & 0xff; // OK
const int c = i & 0xff;
// c's range is fixed and known
b = c; // OK
}
---
)
* For more information, see $(LINK2 https://digitalmars.com/articles/b62.html, the dmc article).
* See also: $(LINK https://en.wikipedia.org/wiki/Value_range_analysis).
$(H2 $(LNAME2 bool, $(D bool)))
$(P The bool type is a byte-size type that can only hold the value `true` or
`false`.)
$(P The only operators that can accept operands of type bool are: $(CODE_AMP)
$(CODE_PIPE), $(D ^), $(CODE_AMP)$(D =), $(CODE_PIPE)$(D =), $(D ^=), !,
$(CODE_AMP)$(CODE_AMP), $(CODE_PIPE)$(CODE_PIPE), and $(D ?:).)
$(P A `bool` value can be implicitly converted to any integral type, with
`false` becoming 0 and `true` becoming 1.)
$(P The numeric literals `0` and `1` can be implicitly converted to the `bool`
values `false` and `true`, respectively. Casting an expression to `bool` means
testing `!=0` for arithmetic types, and `!=null` for
pointers or references.)
$(UNDEFINED_BEHAVIOR)
* Interpreting a value with a byte representation
other than 0 or 1 as `bool` (e.g. an overlapped union field).
* Reading a `void`-initialized `bool`.
$(SPEC_RUNNABLE_EXAMPLE_RUN
---
byte i = 2;
bool b = cast(bool) i; // OK, same as `i != 0`
assert(b);
bool* p = cast(bool*) &i; // unsafe cast
// `*p` holds 0x2, an invalid bool value
// reading `*p` is undefined behavior
---
)
$(H2 $(LNAME2 functions, Function Types))
$(P A function type has the form:)
$(INFORMATIVE_GRAMMAR
$(GLINK2 declaration, StorageClasses)$(OPT) $(GLINK Type) $(GLINK2 function, Parameters) $(GLINK2 function, FunctionAttributes)$(OPT)
)
$(P Function types are not included in the $(GLINK Type) grammar.
A function type e.g. `int(int)` $(DDSUBLINK spec/declaration, alias-function, can be aliased).
A function type is only used for type tests or as the target type of a pointer.)
$(P Instantiating a function type is illegal. Instead, a pointer to function
or delegate can be used. Those have these type forms respectively:)
$(INFORMATIVE_GRAMMAR
$(GLINK Type) `function` $(GLINK2 function, Parameters) $(GLINK2 function, FunctionAttributes)$(OPT)
$(GLINK Type) `delegate` $(GLINK2 function, Parameters) $(GLINK2 function, MemberFunctionAttributes)$(OPT)
)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
void f(int);
alias Fun = void(int);
static assert(is(typeof(f) == Fun));
static assert(is(Fun* == void function(int)));
---
)
$(P See $(DDSUBLINK spec/function, function-pointers, Function Pointers).)
$(H3 $(LNAME2 delegates, Delegates))
$(P Delegates are an aggregate of two pieces of data, either:)
* An object reference and a pointer to a non-static
$(DDSUBLINK spec/class, member-functions, member function).
* A pointer to a closure and a pointer to a
$(DDSUBLINK spec/function, nested, nested function).
The object reference forms the `this` pointer when the function is called.)
$(P Delegates are declared and initialized similarly to function pointers:)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
-------------------
int delegate(int) dg; // dg is a delegate to a function
class OB
{
int member(int);
}
void f(OB o)
{
dg = &o.member; // dg is a delegate to object o and member function member
}
-------------------
)
$(P Delegates cannot be initialized with static member functions
or non-member functions.
)
$(P Delegates are called analogously to function pointers:
)
-------------------
fp(3); // call func(3)
dg(3); // call o.member(3)
-------------------
$(P The equivalent of member function pointers can be constructed
using $(DDSUBLINK spec/expression, function_literals, anonymous lambda functions):)
$(SPEC_RUNNABLE_EXAMPLE_RUN
---
class C
{
int a;
int foo(int i) { return i + a; }
}
// mfp is the member function pointer
auto mfp = function(C self, int i) { return self.foo(i); };
auto c = new C(); // create an instance of C
mfp(c, 1); // and call c.foo(1)
---
)
$(H2 $(LNAME2 typeof, $(D typeof)))
$(GRAMMAR
$(GNAME Typeof):
$(D typeof $(LPAREN)) $(GLINK2 expression, Expression) $(D $(RPAREN))
$(D typeof $(LPAREN)) $(D return) $(D $(RPAREN))
)
$(P
$(D typeof) is a way to specify a type based on the type
of an expression. For example:
)
--------------------
void func(int i)
{
typeof(i) j; // j is of type int
typeof(3 + 6.0) x; // x is of type double
typeof(1)* p; // p is of type pointer to int
int[typeof(p)] a; // a is of type int[int*]
writeln(typeof('c').sizeof); // prints 1
double c = cast(typeof(1.0))j; // cast j to double
}
--------------------
$(P
$(I Expression) is not evaluated, it is used purely to
generate the type:
)
--------------------
void func()
{
int i = 1;
typeof(++i) j; // j is declared to be an int, i is not incremented
writeln(i); // prints 1
}
--------------------
$(P If *Expression* is a
$(DDSUBLINK spec/template, variadic-templates, $(I ValueSeq))
it will produce a *TypeSeq* containing the types of each element.)
$(P Special cases: )
$(OL
$(LI $(D typeof(return)) will, when inside a function scope,
give the return type of that function.
)
$(LI $(LNAME2 typeof-this, $(D typeof(this))) will generate the type of what $(D this)
would be in a non-static member function, even if not in a member
function.
)
$(LI Analogously, $(D typeof(super)) will generate the type of what
$(D super) would be in a non-static member function.
)
--------------------
class A { }
class B : A
{
typeof(this) x; // x is declared to be a B
typeof(super) y; // y is declared to be an A
}
struct C
{
static typeof(this) z; // z is declared to be a C
typeof(super) q; // error, no super struct for C
}
typeof(this) r; // error, no enclosing struct or class
--------------------
)
$(P If the expression is a $(DDSUBLINK spec/function, property-functions,
Property Function), $(D typeof) gives its return type.
)
--------------------
struct S
{
@property int foo() { return 1; }
}
typeof(S.foo) n; // n is declared to be an int
--------------------
$(P If the expression is a $(DDLINK spec/template, Template, Template),
$(D typeof) gives the type $(D void).
)
--------------------
template t {}
static assert(is(typeof(t) == void));
--------------------
$(BEST_PRACTICE
$(OL
$(LI $(I Typeof) is most useful in writing generic
template code.)
)
)
$(H2 $(LNAME2 mixin_types, Mixin Types))
$(GRAMMAR
$(GNAME MixinType):
$(D mixin $(LPAREN)) $(GLINK2 expression, ArgumentList) $(D $(RPAREN))
)
$(P Each $(GLINK2 expression, AssignExpression) in the $(I ArgumentList) is
evaluated at compile time, and the result must be representable
as a string.
The resulting strings are concatenated to form a string.
The text contents of the string must be compilable as a valid
$(GLINK2 type, Type), and is compiled as such.)
---
void test(mixin("int")* p) // int* p
{
mixin("int")[] a; // int[] a;
mixin("int[]") b; // int[] b;
}
---
$(H2 $(LNAME2 aliased-types, Aliased Types))
$(H3 $(LNAME2 size_t, $(D size_t)))
$(P $(D size_t) is an alias to one of the unsigned integral basic types,
and represents a type that is large enough to represent an offset into
all addressable memory.)
$(H3 $(LNAME2 ptrdiff_t, $(D ptrdiff_t)))
$(P $(D ptrdiff_t) is an alias to the signed integral basic type the same size as $(D size_t).)
$(H3 $(LNAME2 string, $(D string)))
$(P A $(DDSUBLINK spec/arrays, strings, $(I string) is a special case of an array.))
$(H3 $(LNAME2 noreturn, $(D noreturn)))
$(P `noreturn` is the $(LINK2 https://en.wikipedia.org/wiki/Bottom_type, bottom type)
which can implicitly convert to any type, including `void`.
A value of type `noreturn` will never be produced and the compiler can
optimize such code accordingly.)
$(P A function that $(DDSUBLINK spec/function, function-return-values, never returns)
has the return type `noreturn`. This can
occur due to an infinite loop or always throwing an exception.)
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
---
noreturn abort(const(char)[] message);
int example(int i)
{
if (i < 0)
{
// abort does not return, so it doesn't need to produce an int
int val = abort("less than zero");
}
// ternary expression's common type is still int
return i != 0 ? 1024 / i : abort("calculation went awry.");
}
---
)
$(P `noreturn` is defined as $(D typeof(*null)). This is because
dereferencing a null literal halts execution.)
$(SPEC_SUBNAV_PREV_NEXT declaration, Declarations, property, Properties)
)
Macros:
CHAPTER=7
TITLE=Types