> On Jul 3, 2017, at 22:44, David Baraff via swift-users 
> <swift-users@swift.org> wrote:
> 
> [I’m from the C++ world of templates and metaprogramming, and I’m shifting 
> from one set of constraints to another.  The swift type system with generics 
> is cool and powerful, but man i’m still trying to really wrap my head around 
> it.  Not that C++ was any easier…]

IIRC, C++ treats templates a bit like "code gen macros" in that it creates a 
different version of the function/type for every value of the template 
parameter. Swift uses protocol witness tables (essentially vtables, if I'm 
remembering my terminology correctly) to achieve something roughly similar, but 
not the same. An important difference, as you've discovered, is that generic 
types are only as constrained as they need to be in their scope. That is, if 
you have a function which takes an unconstrained generic parameter, `T`, it 
doesn't matter if you give in an `Int` at the call site; within that function 
it's just a `T`. More to the point, if you then pass it on to another function 
as you have in your code, it has to go to the version that just takes any type, 
because at the call site for `encode` it's not constrained to be anything else.

Anyway, I hope that helps explain why Swift was behaving differently than you 
were expecting.

- Dave Sweeris
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to