Curiously Recurring Template Pattern

From Crypto++ Wiki
Jump to: navigation, search

Curiously Recurring Template Pattern (CRTP) is a C++ design pattern used extensively by Crypto++. The idiom's name comes from fact that a class will derive from itself as a template argument. CRTP allows a class to achieve compile time polymorphism as opposed to runtime polymorphism.

Curiously Recurring Template Pattern

Curiously Recurring Template Pattern general form is shown below.

template<class T>
struct Base
{
    // methods in Base can access members of Derived
};

struct Derived : public Base<Derived>
{
    // final public type
};

CRTP provides three benefits to the library.

  • Achieves compile time polymorphism
  • Interface with delayed implementation during instantiation
  • Ability to override static class functions.

Compile time polymorphism allows the library to produce smaller objects with less runtime overhead. It general results in faster execution time. Also see What is compile-time polymorphism and why does it only apply to functions? on Stack Overflow.

Curiously Recurring Template Pattern allows the library to select an interface while deferring the implementation until much later when the template is instantiated. Once instantiated, the object enjoys polymorphic behavior.

Finally, CRTP allows the library to override static member functions. For example, StaticAlgorithmName is overriden in derived classes using CRTP. Since an algorithm's name does not need to be selectable at runtime, CRTP works without the runtime overhead of dynamic dispatch. Also see How to override static method of template class in derived class on Stack Overflow.

CRYPTOPP_NO_VTABLE

You will often see CRYPTOPP_NO_VTABLE used in class declarations. It is a preprocessor macro and used to help flatten objects by removing intermediate object vtables. It compliments CRTP.

CRYPTOPP_NO_VTABLE is used with Microsoft compilers on Windows. On Windows the macro expands to __declspec(novtable); while on other platforms it is empty. CRYPTOPP_NO_VTABLE should only be applied to pure interface classes, meaning classes that will never be instantiated on their own.

Application of CRTP

Curiously Recurring Template Pattern is used in practice with the library as follows.

TODO: show how library design combines info classes and derived behavior classes into a final object.