Why is this super class constraint recursive?

In Swift 5 thanks to @Slava_Pestov we can finally use CRTP. I was playing around with it a little and then I tried to construct a CRTP constraint in a protocol, which failed, but I don't understand why:

class Generic<T> {}

protocol P {
  // CRTP with the associated type.
  // I read this as: the conforming type should have a type `A` that
  // is a sub-class of `Generic<A>` (CRTP).
  associatedtype A: Generic<A> // error: Superclass constraint 'Self.A' : 'Generic<Self.A>' is recursive
}
2 Likes

Generic<A> is shorthand for Generic<Self.A>, so the recursion is through Self. We could probably remove the occurs check for superclass constraints without too much fallout; it was mostly intended for same-type constraints (A == Generic<A> is obviously very bad). Do you mind filing a bug?

2 Likes

Sure, will do. I‘m trying to understand what it means for the same type constraint. In case for CRTP even for the same type constraint there shoulnd‘t be any infinite recursion right? But I guess this only true for the general case that does no go through Self.


I had some Swift 5 gymnastics with CRTP today:

class G<T> {
  class S: G<S>
    var t: T
    init(_ t: T) {
      self.t = t
    }
  }
}

let a = G<Int>.S(42)
let b: G<G<Int>.S> = a // works but mind bending at first glance

Filed: https://bugs.swift.org/browse/SR-10239

Would be cool to see this resolved for Swift 5.1

Terms of Service

Privacy Policy

Cookie Policy