Variadic Functions
Part of StandardLibraryCategory
Description
This demo shows typesafe variadic functions (requires DMD 0.93+). It uses std.stdarg and printf.
VariableArgumentsUsingStdStdargExample shows using writef instead of printf.
Example
/* To protect against the vagaries of stack layouts on different CPU architectures, use std.stdarg to access the variadic arguments: */ import std.stdarg; class FOO{} void foo(...) { printf("%d arguments\n", _arguments.length); for (int i = 0; i < _arguments.length; i++) { _arguments[i].print(); if (_arguments[i] == typeid(int)) { int j = va_arg!(int)(_argptr); printf("\t%d\n", j); } else if (_arguments[i] == typeid(long)) { long j = va_arg!(long)(_argptr); printf("\t%lld\n", j); } else if (_arguments[i] == typeid(double)) { double d = va_arg!(double)(_argptr); printf("\t%g\n", d); } else if (_arguments[i] == typeid(FOO)) { FOO f = va_arg!(FOO)(_argptr); printf("\t%p\n", f); } else if (_arguments[i] == typeid(char[])) { char[] c = va_arg!(char[])(_argptr); printf("\t%.*s\n", c); } else assert(0); } } void main() { FOO f = new FOO(); printf("%p\n", f); foo(1, 2, 3L, 4.5, f, "my str"); }
Output
00870FD0 5 arguments int 1 int 2 long 3 double 4.5 FOO 00870FD0
Source
Pieced together from examples in the D Specification.
Link | http://www.dsource.org/tutorials/index.php?show_example=101 |
Posted by | jcc7 |