Here's a simple 2-dimensional C-style array example:
int c[2][2] = {
{ 1, 2 },
{ 3, 4 }
};
If I want this to be std::array
, I have to use this:
std::array<std::array<int, 2>, 2> c = {
{ { 1, 2 } },
{ { 3, 4 } }
};
The declaration is more involved, and I have to use extra {
}
for initialization.
Is it possible to create a C-style array wrapper, with which I can do this?
my_array<int, 2, 2> c = {
{ 1, 2 },
{ 3, 4 }
};
So the declaration is simpler, and there is no need of the extra {
}
.
If creating something like this is possible, would this solution have some drawbacks compared to std::array
?
I've managed to do this:
template <typename T, std::size_t ...S>
struct ArrayTypeHelper;
template <typename T, std::size_t HEAD, std::size_t ...TAIL>
struct ArrayTypeHelper<T, HEAD, TAIL...> {
using Type = typename ArrayTypeHelper<T, TAIL...>::Type[HEAD];
};
template <typename T, std::size_t HEAD>
struct ArrayTypeHelper<T, HEAD> {
using Type = T[HEAD];
};
template <typename T, std::size_t ...S>
struct my_array {
typename ArrayTypeHelper<T, S...>::Type data;
};
But this still needs extra {
}
:
my_array<int, 2, 2> b = { {
{ 1, 2 },
{ 3, 4 }
} };