In C 11, creating a constexpr array of N elements is not as straightforward as in later versions of the language. While constexpr arrays were introduced in C 11, their functionality was limited, and it is not possible to create constexpr arrays of variable length using the same syntax as in C 14 and beyond.
However, using some advanced techniques and constexpr functions, it is possible to achieve similar results in C 11. Here's how:
#include <iostream> template<int N> struct A { constexpr A() : arr() { for (auto i = 0; i != N; ++i) arr[i] = i; } int arr[N]; }; int main() { constexpr auto a = A<4>(); for (auto x : a.arr) std::cout << x << '\n'; }
In this example, we define a constexpr function A
In the main function, we create an instance of A<4> and print the values of the array. Since the array is constexpr, the compiler can determine its values at compile-time, ensuring that no runtime computations are performed for the array.
This approach allows us to create constexpr arrays in C 11, even though the syntax is more complex than in later versions of the language.
The above is the detailed content of How Can I Create a Constexpr Array of N Elements in C 11?. For more information, please follow other related articles on the PHP Chinese website!