Compile-time exceptions
Denis Koroskin
2korden at gmail.com
Mon Nov 24 03:25:11 PST 2008
On Mon, 24 Nov 2008 13:15:36 +0300, bearophile <bearophileHUGS at lycos.com>
wrote:
> 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
This has already been discussed:
http://digitalmars.com/d/archives/digitalmars/D/static_try_catch_construct_would_be_helpful_66794.html
More information about the Digitalmars-d
mailing list