Compile-time exceptions

bearophile bearophileHUGS at lycos.com
Mon Nov 24 02:15:36 PST 2008


This is a generic example of a small function template (it's similar to a function with the same name in Mathematica. It that returns the result of the callable 'func' applied n times to 'item'):


TyItem nest(TyFun, TyItem)(TyFun func, TyItem item, int n) {
    static assert(IsCallable!(TyFun), "nest(): func must be a callable");
    static assert(CastableTypes!(ReturnType!(TyFun), TyItem),
                  "nest(): func must return a type castable to item.");
    if (n < 0)
        throw new ArgumentException("nestList(): n must be >= 0");

    for (int i = 1; i <= n; i++)
        item = func(item);
    return item;
} // End of nest()


Its unit tests contain the following stuff too, because raising that exception is part of the user interface of that function:

unittest {
    ...
    assert(Throws!(ArgumentException)(nest(&sin, 0.1, -1)));
    ...
    //nest("hello", 0.1, -1); // static asserts
    ...
}

(I'm waiting to have a better Throws!() in the std lib that doesn't require to be put into an assert()).
But at the moment I haven't found ways to unit test the first two static asserts, so I just put tests in the unittest for them, and I comment them out to make the unittest run.

That problem may be solved with a "static try" and "static catch", that work at compile time :-)
(I think this isn't related with the Java static exceptions).

static try
    deleg();
static catch (StaticAssert a) {
    ...
}

Bye,
bearophile



More information about the Digitalmars-d mailing list