Questions tagged [crtp]

The curiously recurring template pattern (CRTP) is a C++ idiom in which a class X derives from a class template instantiation using X itself as template argument.

The curiously recurring template pattern (CRTP) is a C++ idiom in which a class X derives from a class template instantiation using X itself as template argument.

The name of this idiom was coined by Jim Coplien, who had observed it in some of the earliest C++ template code.

Typical use cases include static polymorphism and polymorphic copy construction (cloning).

Wikipedia.

758 questions
8
votes
1 answer

Using CRTP with an interface

I have a set of classes that implement the same business methods. I plan to use CRTP instead of virtual dispatch due to performance reasons. But I'd like to keep the convenience of coding to a single interface that comes with inheritance and virtual…
ruipacheco
  • 15,025
  • 19
  • 82
  • 138
8
votes
3 answers

What's the use of the derived class as a template parameter?

What's the purpose of this pattern? What is it called? It looked very strange when I saw it the first time, though I have now seen it many times. template struct Base { //... }; struct Example : Base { //... };
Thomson
  • 20,586
  • 28
  • 90
  • 134
8
votes
3 answers

Template friendship error compilation with GCC but not with clang

This code compiles with clang 3.7.1 (with no diagnostic) but fails with GCC 5.3.0 (live example): #include template struct A { void foo() { static_cast(this)->implementation(); } }; struct Crtp :…
Paolo M
  • 12,403
  • 6
  • 52
  • 73
8
votes
3 answers

Invalid covariant type with CRTP clonable class

I'm trying to implement a Clonable class with the CRTP. However, I need to have abstract class that have a pure virtual clone method, overridden by child classes. To make this happen, I need the clone function to return a covariant return type. I…
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
8
votes
9 answers

Just-In-Time Derivation

There's a less common C++ idiom that I've used to good effect a few times in the past. I just can't seem to remember if it has a generally used name to describe it. It's somewhat related to mixins, CRTP and type-erasure, but is not specifically any…
philsquared
  • 22,403
  • 12
  • 69
  • 98
8
votes
2 answers

Curiously recurring template - variation

Regarding CRP if I want to implement a slight variation of it (using template template parameter) I get a compile error: template