Why does D not have generics?

jmh530 john.michael.hall at gmail.com
Tue Jan 12 22:53:39 UTC 2021


On Tuesday, 12 January 2021 at 22:41:03 UTC, Ola Fosheim Grøstad 
wrote:
> On Tuesday, 12 January 2021 at 22:29:09 UTC, Ola Fosheim 
> Grøstad wrote:
>> On Tuesday, 12 January 2021 at 22:23:51 UTC, Paul Backus wrote:
>>> You have written a generic function that accepts any type 
>>> (unconstrained `T`), but fails to instantiate for most of 
>>> them (e.g. `pop_second!int` would not compile). In a language 
>>> like Rust or Java with type-checked generics, the compiler 
>>> would reject this function definition.
>>
>> Hm? pop_second requires StackConcept!(T,E) ?
>
> Works fine for me:
>
>
> void push(int* x, bool b){ *x = (*x<<1)|b; }
> bool pop(int* x){ bool tmp = *x&1; *x=*x>>1; return tmp; }
> auto as_StackConcept(int* x){ return 
> StackConcept!(int,bool)(x);}
>
>
> void main()
> {
>     int stack = 5;
>     pop_second(&stack);
>     writeln(pop(&stack));
>     writeln(pop(&stack));
> }

What about

auto pop_second(T)(T* obj)
     if (__traits(compiles, {
             T input = T.init;
             auto stack = input.as_StackConcept();
         }))
{
     ...
}


More information about the Digitalmars-d mailing list