Altough itHere is more thoughly explaineda summary of points made by Alex Allain in thehis "Constexpr - Generalized Constant Expressions in C++11", Alex Allain Article, I will simplify it more with a couple simple points.
EDIT: SorryC++11, 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.
" which details Simple explanationthe usefulness of Usefullnessconstexpr:
- First, with a Constexpr
constexprspecifier, the value of the function or variable can be at compile time. - Another benefit of the Constexpr Specifier
constexprspecifier is that it can replace macros with functions - Constexpr
constexprwill also benefit your template metaprogramming.
FinalBenefit to efficiency:
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
ExtraOther benefits:
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 for constexpr functions:
- It must consist of single return statement (with a few exceptions)
- It can call only other constexpr functions
- It can reference only constexpr global variables (Allain 6)
Extras:
Constexpr Constructor Rules for constexpr constructors:
- each of its parameters must be literal type
- the class must have no virtual base classes
- the constructor must not have a function-try-block (CPP 6)
Citations
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
EDIT: Sorry, It was my fault to make it seem like I was the author of these points, so I have corrected myself, changed various parts, and added citations to avoid plagiarism.