Skip to content
Search

C++:const

lastmod 2018-08-17created 2015-06-248 edits

Constexpr

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

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

Constexpr favorite site

References


  1. Constants_and_Constant_Expressions_in_Cpp11_-_CodeProject.pdf ↩