The C++11 standard generalizes the concept of constant
expressions and introduces a new keyword
constexpr as
a declaration specifier. A constant expression is an expression that
can be evaluated at compile time by the compiler. The major benefits
of this feature are as follows:
- Improves type safety and portability of code that requires compile-time
evaluation
- Improves support for systems programming, library building, and
generic programming
- Improves the usability of Standard Library components. Library
functions that can be evaluated at compile time can be used in contexts
that require constant expressions.
An object declaration with the
constexpr specifier
declares that object to be constant. The
constexpr specifier
can be applied only to the following contexts:
- The definition of an object
- The declaration of a function or function template
- The declaration of a static data member of a literal type
If you declare a function that is not a constructor
with a constexpr specifier, then that function is
a constexpr function. Similarly, if you declare a
constructor with a constexpr specifier, then that
constructor is a constexpr constructor.
With
this feature, constant expressions can include calls to template and
non-template constexpr functions, constexpr objects
of class literal types, and references bound to const objects
that are initialized with constant expressions.
Evaluations
of floating-point operations at compile time use the default semantics
of the -qfloat option.