Skip to content

Instantly share code, notes, and snippets.

@neoneye
Created December 18, 2014 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neoneye/af985fac27bc7cdc7836 to your computer and use it in GitHub Desktop.
Save neoneye/af985fac27bc7cdc7836 to your computer and use it in GitHub Desktop.
Curiously recurring template pattern in swift is not working
// https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
class Foo <T: Any> : T {
func hello() { println("hello") }
}
class Bar {
func world() { println("world") }
}
let foobar = Foo<Bar>()
foobar.hello()
foobar.world()
@DevAndArtist
Copy link

DevAndArtist commented Sep 3, 2016

I only know the basics of C++ but even I can see that this is not CRTP here.

If you're interested (after the bug I mention in my blog post is fixed) the following code should work:

protocol Constructor {
    init()
}

protocol Shape {
    func cloned() -> Shape
}

typealias ShapeProtocols = Constructor & Shape

class Shape_CRTP<T> : ShapeProtocols {

    required init() {}

    func  cloned() -> Shape {
        let new = Shape_CRTP<T>()
        // copy everything to `new` from `self`
        return new
    }
}

extension Shape_CRTP where T : ShapeProtocols {

    func cloned() -> Shape {
        let new = T()
        // copy everything to `new` from `self`
        return new
    }
}

// First non-crtp proof of concept
class Square : ShapeProtocols {

    required init() {}
    func cloned() -> Shape {
        return Square()
    }
}

let clone = Shape_CRTP<Square>().cloned() // creates a new `Shape`
type(of: clone) // Square.Type

// now CRTP but this is bugged: http://blog.devandartist.com/posts/swift-crtp
class Circle : Shape_CRTP<Circle> {}

Circle().cloned()

print("this will never print because of the described bug")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment