template type check syntax

Bill Baxter wbaxter at gmail.com
Fri Nov 20 11:40:20 PST 2009


2009/11/20 gzp <galap at freemail.hu>:
> Which is the preferred form ? Shall I place the static assert into the in
> part or into the body directly ?
>
> Is there any difference ? Is there a way to toggle if the in part is
> executed/compiled or not ?  - Like in eifel it can be turned on and off by a
> compiler flag.

I think static asserts are always checked.
Regular asserts are turned off by the -release flag.


> template check1(T) {
>        enum check1 = ...;
> }
>
> bool check2(T t) {
>        return ...;
> }
>
>
> void foo(T)(ref T t)
> in {
>        static assert( check1!(T) );
>        assert(check2(t);
> }
> body {
>        static assert( check1!(T) );
> ...
> }

> Or is there a form like (As i've seen mentioned with future coming opBinary)
> void foo(T)(ref T t) if check1!(T)
> {
>        in {
>                assert(check2(t);
>        }
>        body {
>                ...
>        }
> }

This form exists in D2 (with parens around the check1 part), but the
meaning is slightly different.

The static assert version allows the template to get instantiated but
causes a failure.

The latter form will pass over instantiation of that version of the
template if the "if check1" fails.
It can then go on and try other forms of the template.

For instance you can have this:

void foo(T)(ref T t) if (isPrime!(T)) { ... }
void foo(T)(ref T t) if (!isPrime!(T)) { ... }

But not this:
void foo(T)(ref T t) {  static assert(isPrime!(T); ... }
void foo(T)(ref T t) {  static assert(!isPrime!(T); ... }

because you can't declare two identical templates.


--bb


More information about the Digitalmars-d-learn mailing list