const 는 declaration과 동시에 definition을 해 줘야 한다.
그런데 다음과 같이 runtime 에서야 알 수 있는 const가 있다.
int x;
std::cin >> x; // 입력받은 값을 상수화 시키고 싶다.
const int y = x; // runtime이 되어야만 y값을 알 수 있다.
y = 20 // error!!
입력을 받은 값을 상수화 시키고 싶을 때 이렇게 쓸 수 가 있다.
그렇지만 constexpr 은 반드시 compile 시간에 definition 해줘야만 한다.
constexpr int my_const; // error!!
int x;
cin >> x;
constexpr int y = x; // error!!
추가)
constexpr 은 상수식이라고 명시해 준다고 한다.
https://modoocode.com/293 잘 설명되어있다. 😎
int factorial(int N) {
int total = 1;
for (int i = 1; i <= N; i++) {
total *= i;
}
return total;
}
template <int N>
struct A {
int operator()() { return N; }
};
int main() { A<factorial(5)> a; } //error!
상수값이 와야 한다고 한다. template 이니까!
함수를 constexpr keyword로 상수화 가능하다. 대박...
constexpr int factorial(int N) {
...
}
이러면 해결된다.. 복잡한 meta programming을 피했다.
사용하는것에 제약사항이 있다.