Template constraints in D

janderson askme at me.com
Sat Jun 21 18:13:31 PDT 2008


Dee Girl wrote:
> Walter Bright Wrote:
> 
>> 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).
> 
> Good example is a hashtable. If the bucket size is prime then use a strategy. If is a power of two use another strategy. Otherwise use third strategy. Thanks, Dee Girl

I agree, that's a good example.

-Joel



More information about the Digitalmars-d mailing list