[swift-evolution] Compile-time generic specialization
Joe Groff
jgroff at apple.com
Fri Feb 10 10:40:43 CST 2017
> On Feb 10, 2017, at 8:13 AM, Abe Schneider <abe.schneider at gmail.com> wrote:
>
> Hi Joe,
>
> The issue re-dispatching from a function is that it can make
> maintenance of the library difficult. For every function I define I
> would need to have a large if-else tree. This means that the
> introduction of both new functions and storage types becomes
> expensive. For example, if I had:
>
> func dot<S:Storage>(_ lhs:Tensor<S>, _ rhs:Tensor<S>) -> Tensor<S> {
> if let s = lhs as? Tensor<NativeStorage<Float>> { ... }
> else if if let s = lhs as? Tensor<NativeStorage<Double>> { ... }
> else if let s = lhs as? Tensor<NativeStorage<Int>> { ... }
> if let s = lhs as? Tensor<CBlasStorage<Float>> { ... }
> else if if let s = lhs as? Tensor<CBlasStorage<Double>> { ... }
> else if let s = lhs as? Tensor< CBlasStorage <Int>> { ... }
> if let s = lhs as? Tensor<OpenCLStorage<Float>> { ... }
> else if if let s = lhs as? Tensor< OpenCLStorage <Double>> { ... }
> else if let s = lhs as? Tensor< OpenCLStorage <Int>> { ... }
> }
>
> with the same number of Impls to go along. If I added a new storage
> type (e.g. CUDA) I would have to add each type specified (and I
> haven't added Byte and Short) to every function that can be performed
> on a Tensor (which is currently ~20-30). For my library this doesn't
> lead to maintainable code.
If there's really an independent implementation for each `S: Storage`, then you can make `tensorDot` a requirement of `Storage` and avoid the explosion that way. Ad-hoc type dispatch by either overloading or if chains should be a last resort when protocols really can't model what you're trying to do. Ad-hoc overloading wouldn't really save you any work compared to the if chain—you'd have all the exact problems you mentioned, having to add an overload for every new combo of types, but you'd also have to also think about the implicit relationships among the overloads according to the language's overloading rules instead of in explicit logic.
-Joe
More information about the swift-evolution
mailing list