General features: constexpr

code

Syntax

Usage / Usability

  • Guarantees initialization at compile-time
  • Used as a function qualifier before the function’s return type

Conceptually, constexpr indicates a value that’s not only constant, it’s known during compilation.

  • constexpr functions produce:compile-time constants (when they are called with compile-time constants)
  • Runtime values (when they are called with values not known until runtime)

The main idea is performance improvement of programs by doing computations at compile time rather than run time. (similar to template metaprogramming).
Values evaluated at compile time can be used in other constant expressions.

PROS

  • Allows for more extensive compiler optimization opportunities!
  • Constexpr can be used for both compile-time constants and runtime values.

CONS

  • constexpr functions are limited to taking and returning literal types, which essentially means types that can have values determined during compilation.
  • constexpr is part of an object’s or function’s interface.

 

In C++14, relaxed constrains of constexpr were added.

Leave a comment

Your email address will not be published.