(Note: This question is about not having to specify the number of elements and still allow nested types to be directly initialized.) This question discusses the uses left for a C array like int arr[20];. On his answer, @James Kanze shows one of the last strongholds of C arrays, it's unique initialization characteristics:
We don't have to specify the number of elements, hooray! Now iterate over it with the C++11 functions std::begin and std::end from <iterator> (or your own variants) and you never need to even think of its size.
Now, are there any (possibly TMP) ways to achieve the same with std::array? Use of macros allowed to make it look nicer. :)
??? std_array = { "here", "be", "elements" };
Edit: Intermediate version, compiled from various answers, looks like this:
How to emulate C array initialization "int arr[] = { e1, e2, e3, ... }" behaviour with std::array?
https://ift.tt/zAR5DuG
(Note: This question is about not having to specify the number of elements and still allow nested types to be directly initialized.)
This question discusses the uses left for a C array like
int arr[20];
. On his answer, @James Kanze shows one of the last strongholds of C arrays, it's unique initialization characteristics:We don't have to specify the number of elements, hooray! Now iterate over it with the C++11 functions
std::begin
andstd::end
from<iterator>
(or your own variants) and you never need to even think of its size.Now, are there any (possibly TMP) ways to achieve the same with
std::array
? Use of macros allowed to make it look nicer. :)Edit: Intermediate version, compiled from various answers, looks like this:
And employs all kind of cool C++11 stuff:
sizeof...
std::array
, of courseauto
)And an example can be found here.
However, as @Johannes points out in the comment on @Xaade's answer, you can't initialize nested types with such a function. Example:
Also, the number of initializers is limited to the number of function and template arguments supported by the implementation.
via Stack Overflow
November 20, 2024 at 09:11AM