How do I return `this` from a method of a subclass?

The pattern @Wasabi375 demonstrates, parameterising a class with itself, is pretty common…⠀It seems like a bit of a hack to me, but it’s used in Class, KClass, the parent class of enums, and many other places too.

It’s discussed in this StackOverflow question.

If I understand correctly, it’s basically a work-around for not having self types in the language.

The C++ equivalent apparently rejoices in the name Curiously-Recurring Template Pattern (CRTP).

5 Likes