A small function wrapping writeln and writefln

Andrej Mitrovic none at none.none
Wed Mar 23 10:39:55 PDT 2011


This is just something I was experimenting with:

import std.stdio;
import std.algorithm;

void echo(T...)(T args)
{
    static if (!T.length)
    {
        writeln();
    }
    else
    {
        static if (is(T[0] : string))
        {
            if (canFind(args[0], "%"))
            {
                writefln(args);
                return;
            }
        }
        
        // not a string, or not a formatted string
        writeln(args);
    }
}

void main()
{
    echo("Formatted %s string %s", 1, 2);
    echo("Not a formatted string", 1, 2);
    echo([1, 2, 3]);
}

For a while I've had an issue where I've used `if (is(T[0] : string))`and the compiler complained about instantiating writefln() with an int[] as the first argument. Then I remembered I had to use a static if for compile-time checks (doh!). :)

Of course, the function comes with a cost of a runtime check. But its pretty cool D can do this sort of stuff.


More information about the Digitalmars-d-learn mailing list