D's type classes pattern ?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Mar 24 14:49:23 PDT 2015


On 03/24/2015 08:50 AM, matovitch wrote:

 > Lets say I want to implement some generic algorithm. I would like
 > to checks the types passed to my algorithm implements a specific
 > interface.

I think you are looking for template constraints. Look at isInputRange's 
implementation:

 
https://github.com/D-Programming-Language/phobos/blob/master/std/range/primitives.d#L143

Then you can do:

void foo(Range)(Range range)
    if (isInputRange!Range)    // <--
{
     // ...
}

I have some explanation and examples here:

 
http://ddili.org/ders/d.en/templates_more.html#ix_templates_more.named%20template%20constraint

Ali



More information about the Digitalmars-d-learn mailing list