This repository has been archived by the owner on Sep 23, 2019. It is now read-only.
forked from dlang/dlang.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
function.dd
1753 lines (1391 loc) · 45.3 KB
/
function.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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Ddoc
$(SPEC_S Functions,
$(GRAMMAR
$(GNAME FunctionBody):
$(GLINK2 statement, BlockStatement)
$(GLINK BodyStatement)
$(GLINK InStatement) $(GLINK BodyStatement)
$(GLINK OutStatement) $(GLINK BodyStatement)
$(GLINK InStatement) $(GLINK OutStatement) $(GLINK BodyStatement)
$(GLINK OutStatement) $(GLINK InStatement) $(GLINK BodyStatement)
$(GNAME InStatement):
$(D in) $(GLINK2 statement, BlockStatement)
$(GNAME OutStatement):
$(D out) $(GLINK2 statement, BlockStatement)
$(D out) $(D $(LPAREN)) $(I Identifier) $(D $(RPAREN)) $(GLINK2 statement, BlockStatement)
$(GNAME BodyStatement):
$(D body) $(GLINK2 statement, BlockStatement)
)
$(H4 Function Return Values)
$(P Function return values are considered to be rvalues.
This means they cannot be passed by reference to other functions.
)
$(H4 Functions Without Bodies)
$(P Functions without bodies:)
---
int foo();
---
$(P that are not declared as $(D abstract) are expected to have their implementations
elsewhere, and that implementation will be provided at the link step.
This enables an implementation of a function to be completely hidden from the user
of it, and the implementation may be in another language such as C, assembler, etc.
)
$(H4 $(LNAME2 pure-functions, Pure Functions))
$(P Pure functions are functions which cannot access global or static, mutable
state save through their arguments. This can enable optimizations based on the fact
that a pure function is guaranteed to mutate nothing which isn't passed to it,
and in cases where the compiler can guarantee that a pure function cannot
alter its arguments, it can enable full, functional purity (i.e. the guarantee
that the function will always return the same result for the same arguments).
To that end, a pure function:
)
$(UL
$(LI does not read or write any global or static mutable state)
$(LI cannot call functions that are not pure)
$(LI can override an impure function, but an impure function
cannot override a pure one)
$(LI is covariant with an impure function)
$(LI cannot perform I/O)
)
$(P As a concession to practicality, a pure function can:)
$(UL
$(LI allocate memory via a $(GLINK2 expression, NewExpression))
$(LI terminate the program)
$(LI read and write the floating point exception flags)
$(LI read and write the floating point mode flags, as long as those flags
are restored to their initial state upon function entry)
$(LI perform impure operations in statements that are in a
$(GLINK2 version, ConditionalStatement)
controlled by a $(GLINK2 version, DebugCondition).)
)
$(P A pure function can throw exceptions.)
---
import std.stdio;
int x;
immutable int y;
const int* pz;
pure int foo(int i,
char* p,
const char* q,
immutable int* s)
{
debug writeln("in foo()"); // ok, impure code allowed in debug statement
x = i; // error, modifying global state
i = x; // error, reading mutable global state
i = y; // ok, reading immutable global state
i = *pz; // error, reading const global state
return i;
}
---
$(H4 $(LNAME2 nothrow-functions, Nothrow Functions))
$(P Nothrow functions do not throw any exceptions derived
from class $(I Exception).
)
$(P Nothrow functions are covariant with throwing ones.)
$(H4 $(LNAME2 ref-functions, Ref Functions))
$(P Ref functions allow functions to return by reference.
This is analogous to ref function parameters.
)
---
ref int foo() {
auto p = new int;
return *p;
}
...
foo() = 3; // reference returns can be lvalues
---
$(H4 $(LNAME2 auto-functions, Auto Functions))
$(P Auto functions have their return type inferred from any
$(GLINK2 statement, ReturnStatement)s
in the function body.
)
$(P An auto function is declared without a return type.
If it does not already have a storage class, use the
$(D_KEYWORD auto) storage class.
)
$(P If there are multiple $(I ReturnStatement)s, the types
of them must match exactly. If there are no $(I ReturnStatement)s,
the return type is inferred to be $(D_KEYWORD void).
)
---
auto foo(int i) {
return i + 3; // return type is inferred to be int
}
---
$(H4 $(LNAME2 auto-ref-functions, Auto Ref Functions))
$(P Auto ref functions infer their return type just as
$(LINK2 auto-functions, auto functions) do.
In addition, they become $(LINK2 ref-functions, ref functions)
if the return expression is an lvalue,
and it would not be a reference to a local or a parameter.
)
---
auto ref foo(int x) { return x; } // value return
auto ref foo() { return 3; } // value return
auto ref foo(ref int x) { return x; } // ref return
auto ref foo(out int x) { return x; } // ref return
auto ref foo() { static int x; return x; } // ref return
---
$(P The lexically first $(GLINK2 statement, ReturnStatement)
determines the ref-ness of a function:
)
---
auto ref foo(ref int x) { return 3; return x; } // ok, value return
auto ref foo(ref int x) { return x; return 3; } // error, ref return, 3 is not an lvalue
---
$(H4 $(LNAME2 inout-functions, Inout Functions))
$(P Functions that deal with mutable, const, or immutable types with
equanimity often need to transmit their type to the return value:
)
---
int[] foo(int[] a, int x, int y) { return a[x .. y]; }
const(int)[] foo(const(int)[] a, int x, int y) { return a[x .. y]; }
immutable(int)[] foo(immutable(int)[] a, int x, int y) { return a[x .. y]; }
---
$(P The code generated by these three functions is identical.
To indicate that these can be one function, the $(D_KEYWORD inout)
type constructor is employed:
)
---
inout(int)[] foo(inout(int)[] a, int x, int y) { return a[x .. y]; }
---
$(P The $(D_KEYWORD inout) forms a wildcard that stands in for
any of mutable, const or immutable. When the function is called,
the inout of the return type is changed to whatever the mutable,
const, or immutable status of the argument type to the parameter
inout was.
)
$(P Inout types can be implicitly converted to const, but to nothing
else. Other types cannot be implicitly converted to inout.
Casting to or from inout is not allowed in @safe functions.
)
$(P A set of arguments to a function with inout parameters is considered
a match if any inout argument types match exactly, or:)
$(OL
$(LI No argument types are composed of inout types.)
$(LI A mutable, const or immutable argument type can be matched against each
corresponding parameter inout type.)
)
$(P If such a match occurs, if every match is mutable, then the inout is
considered matched with mutable. If every match is immutable, then the
inout is considered matched with immutable. Otherwise, the inout is
considered matched with const. The inout in the return type is then rewritten
to be the inout matched attribute.
)
$(P Global and static variable types cannot have any inout components.
)
$(P $(B Note:) Shared types are not overlooked. Shared types cannot
be matched with inout.
)
$(H4 $(LNAME2 property-functions, Property Functions))
$(P Property functions are tagged with the $(CODE @property)
attribute. They can be called without parentheses (hence
acting like properties).
)
---
struct S {
int m_x;
@property {
int x() { return m_x; }
int x(int newx) { return m_x = newx; }
}
}
void foo() {
S s;
s.x = 3; // calls s.x(int)
bar(s.x); // calls bar(s.x())
}
---
$(H4 $(LNAME2 virtual-functions, Virtual Functions))
$(P Virtual functions are functions that are called indirectly through a
function pointer table, called a vtbl[], rather than directly. All
$(D public) and $(D protected) member functions which are non-static and
aren't templatized are virtual unless the compiler can determine that
they will never be overridden (e.g. they're marked with $(D final) and
don't override any functions in a base class), in which case, it will
make them non-virtual. This results in fewer bugs caused by not
declaring a function virtual and then overriding it anyway.
)
$(P Member functions which are $(D private) or $(D package) are never
virtual, and hence cannot be overridden.
)
$(P Functions with non-D linkage cannot be virtual and hence cannot be
overridden.
)
$(P Member template functions cannot be virtual and hence cannot be
overridden.
)
$(P Functions marked as $(D final) may not be overridden in a
derived class, unless they are also $(D private).
For example:
)
------
class A {
int def() { ... }
final int foo() { ... }
final private int bar() { ... }
private int abc() { ... }
}
class B : A {
int def() { ... } // ok, overrides A.def
int foo() { ... } // error, A.foo is final
int bar() { ... } // ok, A.bar is final private, but not virtual
int abc() { ... } // ok, A.abc is not virtual, B.abc is virtual
}
void test(A a) {
a.def(); // calls B.def
a.foo(); // calls A.foo
a.bar(); // calls A.bar
a.abc(); // calls A.abc
}
void func() {
B b = new B();
test(b);
}
------
$(P Covariant return types
are supported, which means that the
overriding function in a derived class can return a type
that is derived from the type returned by the overridden function:
)
------
class A { }
class B : A { }
class Foo {
A test() { return null; }
}
class Bar : Foo {
B test() { return null; } // overrides and is covariant with Foo.test()
}
------
$(P Virtual functions all have a hidden parameter called the
$(I this) reference, which refers to the class object for which
the function is called.
)
$(P To avoid dynamic binding on member function call, insert
base class name before the member function name. For example:
)
------
class B {
int foo() { return 1; }
}
class C : B {
override int foo() { return 2; }
void test() {
assert(B.foo() == 1); // translated to this.B.foo(), and
// calls B.foo statically.
assert(C.foo() == 2); // calls C.foo statically, even if
// the actual instance of 'this' is D.
}
}
class D : C {
override int foo() { return 3; }
}
void main() {
auto d = new D();
assert(d.foo() == 3); // calls D.foo
assert(d.B.foo() == 1); // calls B.foo
assert(d.C.foo() == 2); // calls C.foo
d.test();
}
------
$(H4 $(LNAME2 function-inheritance, Function Inheritance and Overriding))
A functions in a derived class with the same name and parameter
types as a function in a base class overrides that function:
------
class A {
int foo(int x) { ... }
}
class B : A {
override int foo(int x) { ... }
}
void test() {
B b = new B();
bar(b);
}
void bar(A a) {
a.foo(1); // calls B.foo(int)
}
------
$(P However, when doing overload resolution, the functions in the base
class are not considered:
)
------
class A {
int foo(int x) { ... }
int foo(long y) { ... }
}
class B : A {
override int foo(long x) { ... }
}
void test() {
B b = new B();
b.foo(1); // calls B.foo(long), since A.foo(int) not considered
A a = b;
a.foo(1); // issues runtime error (instead of calling A.foo(int))
}
------
$(P To consider the base class's functions in the overload resolution
process, use an $(I AliasDeclaration):
)
------
class A {
int foo(int x) { ... }
int foo(long y) { ... }
}
class B : A {
$(CODE_HIGHLIGHT alias A.foo foo;)
override int foo(long x) { ... }
}
void test() {
B b = new B();
bar(b);
}
void bar(A a) {
a.foo(1); // calls A.foo(int)
B b = new B();
b.foo(1); // calls A.foo(int)
}
------
$(P If such an $(I AliasDeclaration) is not used, the derived
class's functions completely override all the functions of the
same name in the base class, even if the types of the parameters
in the base class functions are different. If, through
implicit conversions to the base class, those other functions do
get called, a $(CODE core.exception.HiddenFuncError) exception is raised:
)
---
import core.exception;
class A {
void $(CODE_HIGHLIGHT set)(long i) { }
void set(int i) { }
}
class B : A {
void set(long i) { }
}
void foo(A a) {
int i;
try {
a.set(3); // error, throws runtime exception since
// A.set(int) should not be available from B
}
catch ($(CODE_HIGHLIGHT HiddenFuncError) o) {
i = 1;
}
assert(i == 1);
}
void main() {
foo(new B);
}
---
$(P If an $(CODE HiddenFuncError) exception is thrown in your program,
the use of overloads and overrides needs to be reexamined in the
relevant classes.)
$(P The $(CODE HiddenFuncError) exception is not thrown if the
hidden function is disjoint, as far as overloading is concerned,
from all the other virtual functions is the inheritance hierarchy.)
$(P A function parameter's default value is not inherited:)
------
class A {
void $(CODE_HIGHLIGHT foo)(int x = 5) { ... }
}
class B : A {
void foo(int $(CODE_HIGHLIGHT x = 7)) { ... }
}
class C : B {
void foo(int $(CODE_HIGHLIGHT x)) { ... }
}
void test() {
A a = new A();
a.foo(); // calls A.foo(5)
B b = new B();
b.foo(); // calls B.foo(7)
C c = new C();
c.foo(); // error, need an argument for C.foo
}
------
$(P If a derived class overrides a base class member function with diferrent
$(GLINK2 declaration, FunctionAttributes), the missing attributes will be
automatically compensated by the compiler.)
------
class B {
void foo() pure nothrow @safe {}
}
class D : B {
override void foo() {}
}
void main() {
auto d = new D();
pragma(msg, typeof(&d.foo));
// prints "void delegate() pure nothrow @safe" in compile time
}
------
$(H4 Inline Functions)
There is no inline keyword. The compiler makes the decision whether to
inline a function or not, analogously to the register keyword no
longer being relevant to a
compiler's decisions on enregistering variables.
(There is no register keyword either.)
$(H3 $(LNAME2 function-overloading, Function Overloading))
$(P Functions are overloaded based on how well the arguments
to a function can match up with the parameters.
The function with the $(I best) match is selected.
The levels of matching are:
)
$(OL
$(LI no match)
$(LI match with implicit conversions)
$(LI match with conversion to const)
$(LI exact match)
)
$(P Each argument (including any $(CODE this) pointer) is
compared against the function's corresponding parameter, to
determine the match level for that argument. The match level
for a function is the $(I worst) match level of each of its
arguments.)
$(P Literals do not match $(CODE ref) or $(CODE out) parameters.)
$(P If two or more functions have the same match level,
then $(LNAME2 partial-ordering, $(I partial ordering))
is used to try to find the best match.
Partial ordering finds the most specialized function.
If neither function is more specialized than the other,
then it is an ambiguity error.
Partial ordering is determined for functions $(CODE f())
and $(CODE g()) by taking the parameter types of $(CODE f()),
constructing a list of arguments by taking the default values
of those types, and attempting to match them against $(CODE g()).
If it succeeds, then $(CODE g()) is at least as specialized
as $(CODE f()).
For example:
)
---
class A { }
class B : A { }
class C : B { }
void foo(A);
void foo(B);
void test() {
C c;
/* Both foo(A) and foo(B) match with implicit conversion rules.
* Applying partial ordering rules,
* foo(B) cannot be called with an A, and foo(A) can be called
* with a B. Therefore, foo(B) is more specialized, and is selected.
*/
foo(c); // calls foo(B)
}
---
$(P A function with a variadic argument is considered less
specialized than a function without.
)
$(P Functions defined with non-D linkage cannot be overloaded.
because the name mangling does not take the parameter types
into account.
)
$(H3 $(LNAME2 overload-sets, Overload Sets))
$(P Functions declared at the same scope overload against each
other, and are called an $(I Overload Set).
A typical example of an overload set are functions defined
at module level:
)
---
module A;
void foo() { }
void foo(long i) { }
---
$(P $(CODE A.foo()) and $(CODE A.foo(long)) form an overload set.
A different module can also define functions with the same name:
)
---
module B;
class C { }
void foo(C) { }
void foo(int i) { }
---
$(P and A and B can be imported by a third module, C.
Both overload sets, the $(CODE A.foo) overload set and the $(CODE B.foo)
overload set, are found. An instance of $(CODE foo) is selected
based on it matching in exactly one overload set:
)
---
import A;
import B;
void bar(C c) {
foo(); // calls A.foo()
foo(1L); // calls A.foo(long)
foo(c); // calls B.foo(C)
foo(1,2); // error, does not match any foo
foo(1); // error, matches A.foo(long) and B.foo(int)
A.foo(1); // calls A.foo(long)
}
---
$(P Even though $(CODE B.foo(int)) is a better match than $(CODE
A.foo(long)) for $(CODE foo(1)),
it is an error because the two matches are in
different overload sets.
)
$(P Overload sets can be merged with an alias declaration:)
---
import A;
import B;
alias A.foo foo;
alias B.foo foo;
void bar(C c) {
foo(); // calls A.foo()
foo(1L); // calls A.foo(long)
foo(c); // calls B.foo(C)
foo(1,2); // error, does not match any foo
foo(1); // calls B.foo(int)
A.foo(1); // calls A.foo(long)
}
---
$(P Parameter storage classes are $(D in), $(D out),
$(D ref), $(D lazy), $(D const), $(D immutable), $(D shared),
$(D inout) or
$(D scope).
For example:
)
------
int foo(in int x, out int y, ref int z, int q);
------
$(P x is $(D in), y is $(D out), z is $(D ref), and q is none.
)
$(UL
$(LI The function declaration makes it clear what the inputs and
outputs to the function are.)
$(LI It eliminates the need for IDL as a separate language.)
$(LI It provides more information to the compiler, enabling more
error checking and
possibly better code generation.)
)
$(TABLE_2COLS Parameter Storage Classes,
$(THEAD Storage Class, Description)
$(TROW $(I none), parameter becomes a mutable copy of its argument)
$(TROW $(D in), equivalent to $(D const scope))
$(TROW $(D out), parameter is initialized upon function entry with the default value
for its type)
$(TROW $(D ref), parameter is passed by reference)
$(TROW $(D scope), references in the parameter
cannot be escaped (e.g. assigned to a global variable))
$(TROW $(D lazy), argument is evaluated by the called function and not by the caller)
$(TROW $(D const), argument is implicitly converted to a const type)
$(TROW $(D immutable), argument is implicitly converted to an immutable type)
$(TROW $(D shared), argument is implicitly converted to a shared type)
$(TROW $(D inout), argument is implicitly converted to an inout type)
)
------
void foo(out int x) {
// x is set to int.init,
// which is 0, at start of foo()
}
int a = 3;
foo(a);
// a is now 0
void abc(out int x) {
x = 2;
}
int y = 3;
abc(y);
// y is now 2
void def(ref int x) {
x += 1;
}
int z = 3;
def(z);
// z is now 4
------------
$(P For dynamic array and object parameters, which are passed
by reference, in/out/ref
apply only to the reference and not the contents.
)
$(P $(D lazy) arguments are evaluated not when the function is called,
but when the parameter is evaluated within the function. Hence,
a $(D lazy) argument can be executed 0 or more times. A $(D lazy) parameter
cannot be an lvalue.)
---
void dotimes(int n, lazy void exp) {
while (n--)
exp();
}
void test() {
int x;
dotimes(3, writefln(x++));
}
---
$(P prints to the console:)
$(CONSOLE
0
1
2
)
$(P A $(D lazy) parameter of type $(D void) can accept an argument
of any type.)
$(H4 Function Default Arguments)
$(P Function parameter declarations can have default values:)
---
void foo(int x, int y = 3) {
...
}
...
foo(4); // same as foo(4, 3);
---
$(P Default parameters are evaluated in the context of the
function declaration.
If the default value for a parameter is given, all following
parameters must also have default values.
)
$(H3 $(LNAME2 variadic, Variadic Functions))
Functions taking a variable number of arguments are called
variadic functions. A variadic function can take one of
three forms:
$(OL
$(LI C-style variadic functions)
$(LI Variadic functions with type info)
$(LI Typesafe variadic functions)
)
$(H4 C-style Variadic Functions)
A C-style variadic function is declared as taking
a parameter of ... after the required function parameters.
It has non-D linkage, such as $(D extern (C)):
------
extern (C) int foo(int x, int y, ...);
foo(3, 4); // ok
foo(3, 4, 6.8); // ok, one variadic argument
foo(2); // error, y is a required argument
------
There must be at least one non-variadic parameter declared.
------
extern (C) int def(...); // error, must have at least one parameter
------
$(P
C-style variadic functions match the C calling convention for
variadic functions, and is most useful for calling C library
functions like $(D printf).
)
$(P Access to variadic arguments is done using the standard library
module $(D core.stdc.stdarg).
)
------
import core.stdc.stdarg;
void test() {
foo(3, 4, 5); // first variadic argument is 5
}
int foo(int x, int y, ...) {
va_list ap;
version (X86_64)
va_start(ap, __va_argsave);
else version (X86)
va_start(ap, y); // y is the last named parameter
int z;
va_arg(ap, z); // z is set to 5
va_end(ap);
}
------
$(H4 D-style Variadic Functions)
Variadic functions with argument and type info are declared as taking
a parameter of ... after the required function parameters.
It has D linkage, and need not have any non-variadic parameters
declared:
------
int abc(char c, ...); // one required parameter: c
int def(...); // ok
------
To access them, the following import is required:
------
import core.vararg;
------
These variadic functions have a special local variable declared for
them,
$(D _argptr), which is a $(D core.vararg)
reference to the first of the variadic
arguments. To access the arguments, $(D _argptr) must be used
in conjuction with $(D va_arg):
------
import core.vararg;
void test() {
foo(3, 4, 5); // first variadic argument is 5
}
int foo(int x, int y, ...) {
int z;
z = va_arg!int(_argptr); // z is set to 5
}
------
An additional hidden argument
with the name $(D _arguments) and type $(D TypeInfo[])
is passed to the function.
$(D _arguments) gives the number of arguments and the type
of each, enabling type safety to be checked at run time.
------
import std.stdio;
import core.vararg;
class Foo { int x = 3; }
class Bar { long y = 4; }
void printargs(int x, ...) {
writefln("%d arguments", _arguments.length);
for (int i = 0; i < _arguments.length; i++)
{
writeln(_arguments[i]);
if (_arguments[i] == typeid(int))
{
int j = va_arg!(int)(_argptr);
writefln("\t%d", j);
}
else if (_arguments[i] == typeid(long))
{
long j = va_arg!(long)(_argptr);
writefln("\t%d", j);
}
else if (_arguments[i] == typeid(double))
{
double d = va_arg!(double)(_argptr);
writefln("\t%g", d);
}
else if (_arguments[i] == typeid(Foo))
{
Foo f = va_arg!(Foo)(_argptr);
writefln("\t%s", f);
}
else if (_arguments[i] == typeid(Bar))
{
Bar b = va_arg!(Bar)(_argptr);
writefln("\t%s", b);
}
else
assert(0);
}
}
void main() {
Foo f = new Foo();
Bar b = new Bar();
writefln("%s", f);
printargs(1, 2, 3L, 4.5, f, b);
}
------
which prints:
------
0x00870FE0
5 arguments
int
2
long
3
double
4.5
Foo
0x00870FE0
Bar
0x00870FD0
------
$(H4 Typesafe Variadic Functions)
$(P Typesafe variadic functions are used when the variable argument
portion of the arguments are used to construct an array or
class object.)
$(P For arrays:)
------
int test() {
return sum(1, 2, 3) + sum(); // returns 6+0
}
int func() {
int[3] ii = [4, 5, 6];
return sum(ii); // returns 15
}
int sum(int[] ar ...) {
int s;
foreach (int x; ar)
s += x;