What is the usage of constexpr in C++?
In C++, the keyword ‘constexpr’ is used to declare that an expression or function is a compile-time constant. It can be used in defining constant expressions, variable declarations, function declarations, and other places.
The use of the constexpr keyword allows delaying compile-time constant calculations until compile time, thereby improving program performance. Its main uses include the following aspects:
- Declare a constant expression: using the constexpr keyword, you can declare an expression as a compile-time constant. For example:
constexpr int size = 10;
- Defining Constants: You can declare and define a compile-time constant using the constexpr keyword. For example:
constexpr int factorial(int n) {
return (n <= 1) ? 1 : (n * factorial(n - 1));
}
constexpr int result = factorial(5); // 在编译期间计算factorial(5)的结果并赋值给result
- constexpr关键字可以在声明数组大小时使用,但必须确保数组大小是一个编译时常量。例如:
constexpr int size = 5;
int arr[size]; // 可以使用编译时常量作为数组大小
- The constexpr keyword can be used for template parameters, requiring them to be compile-time constants. For example:
template <int N>
void printArraySize() {
int arr[N];
std::cout << "Array size: " << N << std::endl;
}
constexpr int size = 10;
printArraySize<size>(); // 编译时展开模板,并将size作为常量传递给模板函数
In general, using the constexpr keyword allows programs to perform more calculations during compilation, improving performance, and in some cases avoiding runtime costs.