Why does D not have generics?

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Tue Jan 12 22:41:03 UTC 2021


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));
}


More information about the Digitalmars-d mailing list