Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.
Version 3 (modified by jcc7, 17 years ago)
Tested with DMD 1.0

Variable Arguments using std.stdarg (and std.stdio)

Part of StandardLibraryCategory

Description

This demo shows typesafe variadic functions using std.stdarg and std.stdio. (To protect against the vagaries of stack layouts on different CPU architectures, use std.stdarg to access the variadic arguments)

VariadicFunctionsExample shows using printf.

VariableArgumentsExample shows a similar method of variable arguments using the std.c.stdarg module (which is now obsolete).

Example

module ModName;

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");
}

Sample Batch File

@echo off
set pgm=VariableArgumentsUsingStdStdargExample
dmd %pgm%.d
%pgm%.exe
pause
erase %pgm%.obj
erase %pgm%.map

Output

7 arguments

int     1
int     2
long    3
double  4.5
ModName.FOO     ModName.FOO
float   7
char[]  my str

Required Version

Tested with Digital Mars D Compiler v1.0.