Version 2 (modified by jcc7, 18 years ago) |
---|
Variable Arguments using std.stdarg (and std.stdio)
Part of StandardLibraryCategory
Description
This demo shows typesafe variadic functions using std.stdarg and std.stdio.
VariadicFunctionsExample shows using printf.
VariableArgumentsExample shows a similar method of variable arguments using the std.c.stdarg module (which is now obsolete).
Example
/* To protect against the vagaries of stack layouts on different CPU architectures, use std.stdarg to access the variadic arguments: */ import std.stdarg; import std.stdio; class FOO{} void foo(...) { writefln("%s arguments\n", _arguments.length); for (int i = 0; i < _arguments.length; i++) { writef("%s", _arguments[i].toString); if (_arguments[i] == typeid(int)) { int j = va_arg!(int)(_argptr); writefln("\t%s", j); } else if (_arguments[i] == typeid(long)) { long j = va_arg!(long)(_argptr); writefln("\t%s", j); } else if (_arguments[i] == typeid(float)) { float f = va_arg!(float)(_argptr); writefln("\t%s", f); } else if (_arguments[i] == typeid(double)) { double d = va_arg!(double)(_argptr); writefln("\t%s", d); } else if (_arguments[i] == typeid(FOO)) { FOO f = va_arg!(FOO)(_argptr); writefln("\t%s", f); } else if (_arguments[i] == typeid(char[])) { char[] c = va_arg!(char[])(_argptr); writefln("\t%s", c); } else assert(0); } } void main() { FOO f = new FOO(); foo(1, 2, 3L, 4.5, f, 7F, "my str"); }
Output
7 arguments int 1 int 2 long 3 double 4.5 FOO FOO float 7 char[] my str
Source
Link | http://www.dsource.org/tutorials/index.php?show_example=148 |
Posted by | jcc7 |