Template constraints in D

Walter Bright newshound1 at digitalmars.com
Sat Jun 21 12:41:33 PDT 2008


bearophile wrote:
> They look nice (but I may use a bigger list of examples to understand
> how they can be used). What can they do that can't be done with the
> things already present?
> 
> bool isprime(int n) { ... } template Foo(int N) { static assert
> (isprime(N), "error"); ... }
> 
> 
> template Foo(int N) { static if (N & 1) { // A code } else { // B
> code } Foo!(3)    // instantiates Foo with A code Foo!(64)   //
> instantiates Foo with B code

Very good question. The answer is that the user can add overloads that 
handle more cases without having to edit the original (which may be in a 
module that is not editable for various reasons).



More information about the Digitalmars-d mailing list