Why does D not have generics?
Ola Fosheim Grøstad
ola.fosheim.grostad at gmail.com
Tue Jan 12 21:44:56 UTC 2021
On Tuesday, 12 January 2021 at 21:32:46 UTC, Ola Fosheim Grøstad
wrote:
> 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;
> }
An improvement is to define a helper function:
auto as_stack(T)(T* obj){
auto stack = obj.as_StackConcept();
static assert (is_StackConcept!(typeof(stack)));
return stack;
}
Then you can just do:
auto pop_second(T)(T* obj){
auto stack = obj.as_stack();
auto tmp = stack.pop();
auto tmp2 = stack.pop();
stack.push(tmp);
return tmp2;
}
Or:
auto pop_second(T)(T* obj){
auto tmp = obj.as_stack.pop();
auto tmp2 = obj.as_stack.pop();
obj.as_stack.push(tmp);
return tmp2;
}
More information about the Digitalmars-d
mailing list