Skip to main content
2 of 5
deleted 152 characters in body

Altough it is more thoughly explained in the "Constexpr - Generalized Constant Expressions in C++11", Alex Allain Article, I will simplify it more with a couple simple points.

//EDIT

Sorry, It was my fault to make it seem like I was the author of these points and I have corrected myself and changed various parts and add citations to avoid plagarism.

Simple explanation of Usefullness:

  • First with a Constexpr specifier, the value of the function or variable can be at compile time.
  • Another benefit of the Constexpr Specifier is that it can replace macros with functions
  • Constexpr will also benefit your template metaprogramming.

Final

  • constant expressions allow certain computations to take place at compile time, literally while your code compiles rather than when the program itself is run. (Allain 2)

Performance benefit: if something can be done at compile time, it will be done once, rather than every time the program runs

Extra:

Such variables and functions can then be used where only compile time constant expressions are allowed. A constexpr specifier used in an object declaration implies const. A constexpr specifier used in an function declaration implies inline.(CPP 1)

Some simple rules to remember -

Rules:

  1. It must consist of single return statement (with a few exceptions)
  2. It can call only other constexpr functions
  3. It can reference only constexpr global variables

(Allain 6)

Extras:

Constexpr Constructor Rules:

  1. each of its parameters must be literal type
  2. the class must have no virtual base classes
  3. the constructor must not have a function-try-block

(CPP 6)

Citation:

Allain, Alex, "Constexpr - Generalized Constant Expressions in C++11", Unspecified Date, "http://www.cprogramming.com/c++11/c++11-compile-time-processing-with-constexpr.html"

CPP, "Constexpr Specifier", 16 December 2014, http://en.cppreference.com/w/cpp/language/constexpr