logo

C++ - constexpr

constexpr = constant expression.

Using constexpr = moving computation from runtime to compile time. (it is NOT metaprogramming) A good talk: https://www.youtube.com/watch?v=MdrfPSUtMVM

It can be applied to:

  • variables: compile time constants. constexpr variables are implicitly const,

  • functions: return value is computable at compile time, constexpr member functions are NOT implicitly const. E.g.

    constexpr int Foo() {
      return 42;
    }
    

Define variables constexpr in .cc files or declare them extern const in .h files.

All constexpr functions are implicitly inline

A constexpr function is just an inline function that is allowed to execute at compile time when initializing constant values.