[swift-evolution] Overloading Generic Types

David Sweeris davesweeris at mac.com
Fri Dec 23 14:32:15 CST 2016

(I feel like I’ve already written this... I looked through my sent mail and didn’t see anything, but my sincerest apologies if I started this thread a month ago and forgot about it or something.)

I no longer recall exactly what first made me want to do this (probably something in my on-going “teach the compiler calculus” project), but I’ve been thinking lately that it could be quite handy to overload types themselves based on the value of generic parameters. As a somewhat contrived example:
struct Array <T> { /*everything exactly as it is now*/ }
struct Array <T> where T == Bool { /* packs every 8 bools into a UInt8 for more efficient storage */ }

We can already do this with functions… Conceptually this isn’t any different. As long as the specific version exposes everything the generic version does (easy for the compiler to enforce), I think everything would just work (famous last words). In this example, the subscript function would need to extract the specified bit and return it as a Bool instead of simply returning the specified element. The `Element` typealias would be `Bool` instead of `UInt8`, which would mean the size/stride might be different than expected (but that’s why we have `MemoryLayout<>`).

Anyway, because generic structs & functions already can’t make assumptions about a generic argument (beyond any constraints, of course), I think this should be in phase 2… but I’m quite hazy on how generics work once the code’s been compiled, so maybe not.

- Dave Sweeris

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161223/055ccb9e/attachment.html>

More information about the swift-evolution mailing list