Zach Saw
Zach Saw

Reputation: 4378

Replicating C++/CLI multidimensional array template class in standard C++

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.

Upvotes: 2

Views: 699

Answers (2)

Kargath
Kargath

Reputation: 528

In C++23, you can use this syntax in standard C++.
Related Links:
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2128r6.pdf https://eel.is/c++draft/over.sub

Upvotes: 0

Antoine
Antoine

Reputation: 14084

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 like array(i, j)
  • Use a proxy class for arguments, e.g. array[makeIndex(i, j)]
  • Using comma operator: array[makeIndex(i), makeIndex(j)]
  • Or 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 IndexBegin is IndexList<0>, IndexList<N> [comma] int is IndexList<N+1>. Then if your array also know its dimension statically, like a 2D array is Array<2> then you can check at compile time that a 2D array only accepts 2 indices.

Upvotes: 3

Related Questions