May I ask what are the differences in generics vs templates except for slightly different syntax? I've tried to understand it from the Manual but to me it seems that they have the same use-case. I've tried searching for some discussion about this but couldn't find anything, perhaps it's clear to everybody but me.
What can be done with one and not another? Thanks.
They're both a variation of metaprogramming, but their semantics are slightly different. A template is code substitution that substitutes at every invocation whereas a generic only generates a procedure once on it's first invocation.
proc doThing(a: auto) =
mixin otherThing
otherThing(a)
template doThing2(a: auto) =
otherThing(a)
proc otherThing(a: auto) = echo a
doThing("hello")
doThing2("hello")
proc otherThing(s: string) = echo "hmm"
doThing("hello")
doThing2("hello")
Demonstrates this difference, also since generic procedures are actual procedure you can use them as pointer procedures:
var a = (proc(s: string))(doThing)
a("hello")
So in reality to use a template one needs a template that emits a specific procedure
template emitDoThing(typ: typedesc) =
proc doThing(val: typ) =
otherThing(val)
emitDoThing(string)
doThing("hello")
var a = (proc(s: string))(doThing)
Always wanted to know how to do this, thanks @eb