D's type classes pattern ?

matovitch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Mar 24 09:56:11 PDT 2015


On Tuesday, 24 March 2015 at 16:44:54 UTC, weaselcat wrote:
> On Tuesday, 24 March 2015 at 15:51:00 UTC, matovitch wrote:
>> Hi,
>>
>> It's been a long time since I coded some d code... sorry I take
>> the lazy way asking for advices. :D
>>
>> Lets say I want to implement some generic algorithm. I would 
>> like
>> to checks the types passed to my algorithm implements a 
>> specific
>> interface.
>>
>> interface IStuff(Stuff)
>> {
>>     void foo();
>> }
>>
>> class TypeClass(T, I) : I(T)
>> {
>>     alias this T;
>> }
>>
>> void myAwesomeAlgo(Stuff) (TypeClass!(Stuff, IStuff) stuff)
>> {
>>     stuff.foo();
>> }
>>
>>
>> Well it seems that I have worked out my question in trying to
>> formulate it...Would something like this work ?
>
> interface Foo{
> }
> void Bar(T : Foo)(T t){
> }
>
> but interfaces enable runtime polymorphism, you can just accept 
> the interface itself
> void Fun(Foo foo){
> }


Thanks, just to be clear :

void Bar(T : Foo)(T t){
}

is the same as

void Bar(T)(T t) if (is(T == Foo)){
}

and it is checked only at compile time ? (for the runtime I know 
that what interface were meant for ;)).




More information about the Digitalmars-d-learn mailing list