[swift-users] still wrestling with a type conversion problem

David Sweeris davesweeris at mac.com
Tue Jul 4 13:29:27 CDT 2017


> On Jul 3, 2017, at 22:44, David Baraff via swift-users <swift-users at 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170704/d85f723d/attachment.html>


More information about the swift-users mailing list