Home >Backend Development >C++ >How Can I Mimic C-Style Array Initialization with `std::array` in C ?
In C programming, array initialization can be simplified using the syntax int arr[] = { e1, e2, e3, ... }, where the number of elements is automatically inferred. While std::array provides a modern alternative to C arrays, it lacks this convenient initialization method. This article explores techniques to emulate this behavior with std::array.
One approach involves a variadic template function:
template<class T, class... Tail> auto make_array(T head, Tail... tail) -> std::array<T, 1 + sizeof...(Tail)> { std::array<T, 1 + sizeof...(Tail)> a = { head, tail ... }; return a; }
This function takes an initial element head and any number of additional elements as tail. It creates a std::array of the appropriate size, initializing it with the provided elements. For instance, the code auto a = make_array(1, 2, 3); initializes a std::array containing the elements 1, 2, and 3.
However, this approach faces limitations. It relies on the compiler's ability to optimize out the copy of the returned value, which may not always be reliable. Additionally, it cannot initialize nested types, a feature supported by C array initialization. To overcome these limitations, consider the following improvements:
#define ARRAY(...) make_array(__VA_ARGS__)
template<class T, class... Tail> auto make_array(std::array<T, Size> head, Tail... tail) -> std::array<T, Size + sizeof...(Tail)> { std::array<T, Size + sizeof...(Tail)> a = { head, tail ... }; return a; }
Using these improvements, nested type initialization becomes possible, as seen in the example:
#define ARRAY(...) make_array(__VA_ARGS__) struct A { int a; int b; }; auto arr = ARRAY(A{1, 2}, A{3, 4});
These techniques provide a robust solution for emulating C array initialization with std::array, enabling convenient and concise initialization of std::array objects in modern C code.
The above is the detailed content of How Can I Mimic C-Style Array Initialization with `std::array` in C ?. For more information, please follow other related articles on the PHP Chinese website!