top of page

constexpr polymorphism

Constexpr polymorphism


C++20 introduced many new and exciting features.

One of those features is "constexpr polymorphism"


Pre-C++20, we couldn't just use virtual functions in compile time because virtual keyword represented runtime polymorphism. If we wanted to run polymorphism in compile time, we had to use some template tricks.


In C++20, P1064 was implemented, it is a very simple change, and it removes the requirement on constexpr functions that they shall not be virtual.


Because of that, we can now use "virtual constexpr" and use constexpr polymorphism in a very straightforward way.


Look at the next example; in this example, we are creating a base class for Animal and then inheriting from it when we create Cat and Duck class. Notice that we are using constexpr and virtual in the same line and creating a virtual function that can work during compile-time.

Then we have a function that iterates over a container of animals and counts the number of legs. This function then runs on a constexpr Cat and Duck instance and counts the number of legs in static_assertion. This means we can write compile-time polymorphism in a very simple and clean way.






Comments


bottom of page