const Vs constexpr
With C++11, WG21 comity introduced generalized constant expression to be able to use in C++ as compile time evaluated constants, and only be used on where its value is evaluated to a const expression. It should have the following requirements:
As a Variable:
As a Variable:
- it must be immediately constructed or assigned a value.
- the constructor parameters or the value to be assigned must contain only literal values,
constexprvariables and functions.
- the constructor used to construct the object (either implicit or explicit) must satisfy the requirements of
constexprconstructor. In the case of explicit constructor, it must have constexpr specified.
As a Function:
- it must not be virtual
- its return type must be
LiteralType - each of its parameters must be literal type
- the function body must be either deleted or defaulted or contain only the following:
- null statements
static_assertdeclarationstypedefdeclarations and alias declarations that do not define classes or enumerations- using declarations
- using directives
- exactly one
returnstatement that contains only literal values,constexprvariables and functions.
As a Constructor:- each of its parameters must be literal type
- the class must have no virtual base classes
- the constructor body must be either deleted or defaulted or contain only the following:
- null statements
static_assertdeclarationstypedefdeclarations and alias declarations that do not define classes or enumerations- using declarations
- using directives
- the constructor must not have a function-try block
- every base class and every non-static member must be initialized, either in the
initializer_listor by brace-or-equal initializer. In addition, every constructor involved must be a constexpr constructor and every clause of every brace-or-equal initializer must be a constant expression - every implicit conversion involved must be a constant expression
See the below papaer for more information:
Comments
Post a Comment