C++:const
lastmod 2018-08-17created 2015-06-248 edits
Constexpr
- [Recommended] MSDN: constexpr(C++)
- constexpr specifier (since C++11)
constexpr specifies that the value of a variable or function can appear in constant expressions. That is, work that can be treated as constant can be handled at compile time.
constexpr variable requirements
A constexpr variable must satisfy the following requirements:
- its type must be a LiteralType.
- it must be immediately constructed or assigned a value.
- the constructor parameters or the value to be assigned must contain only literal values, constexpr variables and functions.
- the constructor used to construct the object (either implicit or explicit) must satisfy the requirements of constexpr constructor. In the case of explicit constructor, it must have constexpr specified.
constexpr function requirements
A constexpr function must satisfy the following requirements:
- it must not be virtual
- its return type must be LiteralType
- each of its parameters must be literal type
- there exists at least one argument value such that an invocation of the function could be an evaluated subexpression of a core constant expression (for constexpr function templates, at least one specialization must satisfy this requirement , for constructors, use in a constant initializer is sufficient)
static constexpr
- Stackoverflow: undefined reference when accessing static constexpr float member
- Stackoverflow: C++ Linker Error With Class static constexpr
- Stackoverflow: Undefined reference to static constexpr char array
Troubleshooting
Multiple definition of a const char*
Using const char * causes a duplicate declaration error.
For char*, declare it as const char * const.
Favorite site
- CodeProject.com: Constants and Constant Expressions in C++11 1
- Stackoverflow: Understanding static constexpr member variables
Constexpr favorite site
- constexpr specifier (since C++11)
- Constant expressions
- [Recommended] C++11 constexpr
- C++14 New features: relaxed constexper restrictions
- constexpr variables
- Stackoverflow: Difference between
constexprandconst
References
-
Constants_and_Constant_Expressions_in_Cpp11_-_CodeProject.pdf ↩
Pages that link here