Practical Uses for the “Curiously Recurring Template Pattern”

后端 未结 5 1565
孤街浪徒
孤街浪徒 2020-11-30 22:47

What are some practical uses for the \"Curiously Recurring Template Pattern\"? The \"counted class\" example commonly shown just isn\'t a convincing example to me.

5条回答
  •  悲&欢浪女
    2020-11-30 23:24

    It's also especially useful for mixins (by which I mean classes you inherit from to provide functionality) which themselves need to know what type they are operating on (and hence need to be templates).

    In Effective C++, Scott Meyers provides as an example a class template NewHandlerSupport. This contains a static method to override the new handler for a particular class (in the same way that std::set_new_handler does for the default operator new), and an operator new which uses the handler. In order to provide a per-type handler, the parent class needs to know what type it is acting on, so it needs to be a class template. The template parameter is the child class.

    You couldn't really do this without CRTP, since you need the NewHandlerSupport template to be instantiated separately, with a separate static data member to store the current new_handler, per class that uses it.

    Obviously the whole example is extremely non-thread-safe, but it illustrates the point.

    Meyers suggests that CRTP might be thought of as "Do It For Me". I'd say this is generally the case for any mixin, and CRTP applies in the case where you need a mixin template rather than just a mixin class.

提交回复
热议问题