cpp / expert
Snippet
Constexpr Virtual Functions for Compile-Time Class Hierarchies
Introduced in C++20, constexpr virtual functions allow dynamic dispatch to be evaluated entirely during compilation when objects are constructed and invoked within a constant expression context. This integrates object-oriented hierarchy design directly with compile-time metaprogramming and static assertion checks.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>class Shape {public:constexpr virtual double area() const = 0;constexpr virtual ~Shape() = default;};class Rectangle : public Shape {public:constexpr Rectangle(double w, double h) : width_(w), height_(h) {}constexpr double area() const override { return width_ * height_; }private:double width_, height_;};class Circle : public Shape {public:constexpr explicit Circle(double r) : radius_(r) {}constexpr double area() const override { return 3.141592653589793 * radius_ * radius_; }private:double radius_;};constexpr double total_area(const Shape& s1, const Shape& s2) {return s1.area() + s2.area();}int main() {constexpr Rectangle rect(4.0, 5.0);constexpr Circle circ(3.0);constexpr double combined = total_area(rect, circ);static_assert(combined > 48.0 && combined < 49.0, "Compile-time calculation failed");std::cout << "Compile-time evaluated dynamic area: " << combined << '\n';}
Breakdown
1
constexpr virtual double area() const = 0;
Declares virtual member function usable during compile-time constant evaluation.
2
constexpr double combined = total_area(rect, circ);
Performs polymorphic dynamic dispatch inside a constexpr expression.
3
static_assert(combined > 48.0 && combined < 49.0, "...");
Verifies the polymorphic calculation result statically at compile-time.