Why does D not have generics?

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Tue Jan 12 21:32:46 UTC 2021


So, this is one, perhaps clumsy way of doing it:


import std.stdio;

struct StackConcept(T,E) {
     alias self_type = T;
     alias element_type = E;
	T* self;
     this(T* obj){ self = obj; }
     pragma(inline,true) void push(E x){ self.push(x); }
     pragma(inline,true) E pop(){ return self.pop(); }
}

template is_StackConcept(T) {
     enum bool is_StackConcept = 
is(StackConcept!(T.self_type,T.element_type)==T);
}

struct intstack {
     int[] arr = [];
     void push(int x){ arr.length++; arr[$-1] = x; }
     int pop(){ auto tmp=arr[$-1]; arr.length--; return tmp; }

     auto as_StackConcept(){
     	return StackConcept!(intstack,int)(&this);
	}
}

auto pop_second(T)(T* obj){
     auto stack = obj.as_StackConcept();
     static assert (is_StackConcept!(typeof(stack)));
	auto tmp = stack.pop();
     auto tmp2 = stack.pop();
     stack.push(tmp);
     return tmp2;
}

void main()
{
     intstack stack;
     stack.push(1);
     stack.push(2);
     stack.push(3);
     pop_second(&stack);
     writeln(stack.pop());
     writeln(stack.pop());
}



More information about the Digitalmars-d mailing list