constexpr and Moving Work to the Build

Templates compute with types. constexpr computes with values, using ordinary function syntax, and since C++20 it can do almost everything ordinary code can. It is the more practical half of compile-time programming and the one that appears most often in real trading code.

Can, will, and must

Three keywords, and the distinction between them is a standard interview question.

constexpr
MeansMay run at compile time, if the arguments allow
Applied toFunctions and variables
With run-time argumentsFalls back to a normal call
Use forAnything that could be constant-folded
consteval
MeansMust run at compile time, always
Applied toFunctions
With run-time argumentsCompilation error
Use forGuaranteeing no run-time fallback
constinit
MeansMust be initialised at compile time
Applied toVariables
With run-time argumentsNot applicable
Use forAvoiding static initialisation order problems

constexpr is a permission. consteval is a requirement. constinit is about when the value is ready.

The trap is assuming constexpr guarantees anything. A constexpr function called with a run-time value is an ordinary function call, silently. If the point is that the work must not happen at run time, the answer is consteval, or forcing the result into a constexpr variable so it has to be a constant expression.

The rest of this lesson is for subscribers

Unlock every lesson in Systems Programming for Trading, and every other premium course.

Subscribe to continue

Test your knowledge

Questions are only available to subscribers.

Keep reading Systems Programming for Trading

19 lessons in this course, and every other premium course, on one subscription.

  • Every lesson in every course, with the worked examples and interactive simulators
  • Graded questions on every lesson, with explanations for the wrong answers as well as the right one
  • The trainers, timed assessments and brainteaser library that go with them