I really can\'t find any use of it. My first idea was that I could use it to implement \'Design by Contract\' without using macros like this:
struct S
{
S
Here is a summary of points made by Alex Allain in his "Constexpr - Generalized Constant Expressions in C++11," which details the usefulness of constexpr
:
constexpr
specifier, the value of the function or variable can be at compile time. constexpr
specifier is that it can replace macros with functions constexpr
will also benefit your template metaprogramming.Benefit 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
Other 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)
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)
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)
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.