Ah, simple solution to unittests inside templates

Nick Treleaven via Digitalmars-d digitalmars-d at puremagic.com
Thu Sep 22 12:38:44 PDT 2016


On Sunday, 18 September 2016 at 12:16:54 UTC, Andrei Alexandrescu 
wrote:
> I don't see that as much of a hurdle seeing as any template 
> written has a few "obvious" types it'll work with. To 
> encapsulate that if needed:
>
> struct Awesome(A, B, C)
> {
>     private enum ut = is(A == int) && is(B == int) && is(C == 
> int);
>     unittest { alias Awe = Awesome!(int, int, int); }
>
>     static if (ut) unittest
>     {
>         ...
>     }
> }

I like how the non-static unittest ensures that any instantiation 
of Awesome triggers the static unittest. I've encapsulated this 
pattern into a template:

https://github.com/ntrel/stuff/blob/master/testinstanceflag.d#L34

Awesome would then just need one line instead of two before the 
'static if' line:

private enum ut = testInstanceFlag!(Awesome, int, int, int);

(testInstanceFlag currently only works with one argument though). 
The nice thing is that people reading the source can look up the 
docs for testInstanceFlag to learn about it.


More information about the Digitalmars-d mailing list