D's type classes pattern ?

matovitch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 25 03:08:54 PDT 2015


On Wednesday, 25 March 2015 at 08:55:14 UTC, bearophile wrote:
> matovitch:
>
>> I am curious to know how isInputRange is implemented since I
>> wanted to do kind of the same but I am afraid it's full of 
>> (ugly)
>> traits and template trickeries where haskell type classes are
>> quite neat and essentially a declaration of an interface.
>
> Take a look at the sources and learn. They are sometimes tricky 
> to get right, but it's not a problem of ugly syntax.
>
>
>> I wondered if you could check statically that the type could
>> implement an interface *if it wanted to* that is, without
>> inheriting it...
>
> Template constraints don't require inheritance.
>
> Bye,
> bearophile

Yes I know that you don't need to inherit some InputRange 
interface to be able to check a user defined type is an input 
range. And template constraints are more powerful/general than 
type classes but it's harder to get right for the beginner. I 
will definetly look at the code anyway.

I was looking at :

interface IInputRange(InputRange) {...}

class TypeClass(T,I) : I!T
{
     alias t this;
     T t;
}

void foo(InputRange) (InputRange inputRange) if 
(isInstanciable(TypeClass!(InputRange, IInputRange)));


More information about the Digitalmars-d-learn mailing list