Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

constexpr virtual functions

Use case

Polymorphism at compile-time.

Explanation

Virtual functions can be constexpr in C++20, enabling compile-time polymorphism.

Code

#include <cstdint>
#include <iostream>

struct Arch {
  virtual constexpr uint32_t pointerSize() const = 0;
  virtual constexpr ~Arch() = default;
};

struct ARM64 : Arch {
  constexpr uint32_t pointerSize() const override { return 8; }
};

struct ARM32 : Arch {
  constexpr uint32_t pointerSize() const override { return 4; }
};

template <typename T> constexpr uint64_t stackAlloc(int count) {
  T arch;
  return arch.pointerSize() * count;
}

int main() {
  constexpr auto size = stackAlloc<ARM64>(4);
  static_assert(size == 32, "Stack alloc is expected to be 32 bytes.");
  std::cout << "Stack alloc: " << size << " bytes.\n";
  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/constexpr-virtual-functions
Stack alloc: 32 bytes.