[swift-evolution] Compile-time generic specialization

David Sweeris davesweeris at mac.com
Mon Feb 20 14:58:31 CST 2017


> On Feb 20, 2017, at 12:23, Abe Schneider via swift-evolution <swift-evolution at swift.org> wrote:
> 
> However, if I define an operation to on the Tensor:
> 
> class SomeOp<S:Storage> {
>     typealias StorageType = S
>     var output:Tensor<S>
>     
>     init() {
>         output = Tensor<S>(size: 10)
>     }
>     
>     func apply() -> Tensor<S> {
>         let result = T.cos(output)
>         return result
>     }
> }
> 
> let op1 = SomeOp<FloatStorage>()
> let result3 = op1.apply() // calls default `cos` instead of FloatStorage version
> 
> 
> 
> So one question I have is why doesn’t the correct version of `cos` get called? Before it was because there wasn’t a vtable available to figure out which function to call. However, in this case since the function was defined in the class, I would assume there would be (I also tried variants of this with an accompanying protocol and non-static versions of the function).
> 
> 
> I can get `SomeOp` to work correctly if I create specializations of the class:
> 
> extension SomeOp where S:FloatStorage {
>     func apply() -> Tensor<S> {
>         let result = T.cos(output)
>         return result
>     }
> }
> 
> extension SomeOp where S:IntStorage {
>     func apply() -> Tensor<S> {
>         let result = T.cos(output)
>         return result
>     }
> }
> 
> 
> However, this doesn’t seem like a good design to me, as it requires copying the same code for each StorageType introduced.

Where is T defined? What happens if you replace "T" with "Tensor<S>"?

- Dave Sweeris 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170220/faf8b413/attachment.html>


More information about the swift-evolution mailing list