In C++/CLI, you can specify the following for multidimensional arrays.
array<int, 2>^ Foo = gcnew array<int, 2>(10);
Foo[0, 0] = 1;
Foo[1, 0] = 2;
// ...
I’m trying to replicate the above in the closest syntax possible in standard C++ (C++11 is allowed) via a templated class called my_array.
e.g.
template <typename T, int rank = 1>
class my_array { };
Is it possible via some comma operator overloading tricks to achieve C++/CLI’s syntax under standard C++, along with overriding my_array’s subscript operator?
Ideally, I’d like the my_array used this way (equivalent to the above example):
my_array<int, 2> Foo = // ... (ignore this part - already implemented)
Foo[0, 0] = 1;
Foo[1, 0] = 2;
// ...
In case anyone’s wondering, I’m creating a C++/CLI equivalent for GCC and currently the framework does not support multidimensional arrays. I’m looking to add that functionality in the closest possible way syntax wise to C++/CLI.
No it is not possible in standard C++. Indeed
operator[]can only take a single argument.You may achieve similar syntax using one of these solutions:
operator()with several arguments likearray(i, j)array[makeIndex(i, j)]array[makeIndex(i), makeIndex(j)]array[IndexBegin, i, j].See also this and that questions.
— Optimization note —
In you go the comma route, you’ll be building dynamic lists with the comma operator, and the array will be checking the length of these lists. In a naive implementation these checks will be run-time and redundant (when used in a loop).
Better option: use lists of statically known length (with templates) Like
IndexBeginis IndexList<0>,IndexList<N> [comma] intisIndexList<N+1>. Then if your array also know its dimension statically, like a 2D array isArray<2>then you can check at compile time that a 2D array only accepts 2 indices.