IdiomsPolymorphismTemplates

Idioms for Polymorphism and Templates

This post is unique because I have written about all the topics mentioned in this post already. Therefore, I only provide a few words about the topic and a link to the post mentioned.

 IdiomsPolymorphismTemplates

I decided on this particular post for two reasons. First, all the idioms for polymorphism and templates in C++ are very important and often used. Second, I don’t write posts about topics I have already a few months ago written about.

Polymorphism

Polymorphism is the property that different types support the same interface. In C++, we distinguish between dynamic polymorphism and static polymorphism.

Dynamic Polymorphism

Dynamic Polymorphism takes place at run time, based on object orientation, and enables us to separate between the interface and the implementation of a class hierarchy. To get late binding, dynamic dispatch, or dispatch at run time, you need virtuality and an indirection such as a pointer or a reference.

Curiously Recurring Template Pattern (CRTP)

Here is the crucial idea of CRTP: A class Derived derives from a class template Base, and Base has Derived as a template argument.

template <typename T>
class Base {
    ...
};

class Derived : public Base<Derived> {
    ...
};

 

Static polymorphism is based on CRTP.

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (open)
  • "Generic Programming (Templates) with C++": October 2024
  • "Embedded Programming with Modern C++": October 2024
  • "Clean Code: Best Practices for Modern C++": March 2025
  • Do you want to stay informed: Subscribe.

     

    Static Polymorphism

    Static polymorphism happens at compile time and has no runtime performance cost.

    The Overload Pattern

    Typically, you use the overload pattern for a std::variant. std::variant is a type-safe union. with one value from one of its types. std::visit allows you to apply a visitor to it. Exactly here comes the Overload Pattern in C++20 very handy in play.

    template<typename ... Ts> 
    struct Overload : Ts ... { 
        using Ts::operator() ... ; 
    };
    

     

    Templates

    Templates extend C++ with many new idioms.

    Mixins

    Mixins are a popular idea in the design of classes to mix in new code. You can implement mixins in C++ by using CRTP. A prominent example is the class std::enable_shared_from_this.

    Expression Templates

    Expression templates are typically used in linear algebra and are  “structures representing a computation at compile-time, which structures are evaluated only as needed to produce efficient code for the entire computation” (https://en.wikipedia.org/wiki/Expression_templates). In other words, expression templates are only evaluated when needed. 

    Policy

    A policy is a generic function or class whose behavior can be configured. Typically, there are default values for the policy parameters. std::vector and std::unordered_map exemplify this design idea in the Standard Template Library.

    template<class T, class Allocator std::allocator<T>>        
    class vector; 
    
    template<class Key,
        class T,
        class Hash = std::hash<Key>,                               
        class KeyEqual = std::equal_to<Key>,                       
        class allocator = std::allocator<std::pair<const Key, T>>  
    class unordered_map;
    

     

    Traits

    Traits are class templates that provide characteristics of a generic type. They can extract one or more characteristics of a class template.

    Tag Dispatching

    Tag dispatching is a way to simulate function overloading based on concepts, often based on traits.

    Type Erasure

    Type Erasure enables using various concrete types through a single generic interface. In C, you base it on void pointers; in C++, on object orientation or templates.

    What’s Next?

    I’m happy to present in my next post a guest post from Alex Eisenhut. Alex will write about his passion: good software architecture.

     

     

     

     

     

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Modernes C++ GmbH

    Modernes C++ Mentoring (English)

    Do you want to stay informed about my mentoring programs? Subscribe Here

    Rainer Grimm
    Yalovastraße 20
    72108 Rottenburg

    Mobil: +49 176 5506 5086
    Mail: schulung@ModernesCpp.de
    Mentoring: www.ModernesCpp.org

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *