Skip to content

C++:const

Constexpr

constexpr는 변수 또는 함수의 값이 상수 표현에 나타날 수 있음을 지정합니다. 즉 상수로 취급할 수 있는 작업은 컴파일 타임에 처리하도록 할 수 있다.

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*

const char *를 사용할 경우 중복 선언 에러가 발생된다.

char*의 경우 const char * const로 선언해야 한다.

Favorite site

Constexpr favorite site

References


  1. Constants_and_Constant_Expressions_in_Cpp11_-_CodeProject.pdf