Reputation: 958
I want to define a 3D array like this:
Type ary[3/*enumeration type*/][6/*int*/][7/*const wchar**/];
Is it possible in C++? I'm using Visual Studio 2010, Boost library is not allowed. If it's possible, please tell me how to initialize each dimension?
Upvotes: 1
Views: 133
Reputation: 217135
Following may help you:
template <typename T, std::size_t N, typename IndexType>
class typed_array
{
public:
typedef typename std::array<T, N>::const_iterator const_iterator;
typedef typename std::array<T, N>::iterator iterator;
public:
const T& operator [] (IndexType index) const { return array[int(index)]; }
T& operator [] (IndexType index) { return array[int(index)]; }
// discard other index type
template <typename U> const T& operator [] (U&&) const = delete;
template <typename U> T& operator [] (U&&) = delete;
const_iterator begin() const { return array.begin(); }
const_iterator end() const { return array.end(); }
iterator begin() { return array.begin(); }
iterator end() { return array.end(); }
private:
std::array<T, N> array;
};
enum class E { A, B, C };
int main(int argc, char *argv[])
{
typed_array<int, 3, E> a;
typed_array<typed_array<int, 4, char>, 3, E> b;
//a[2] = 42; // doesn't compile as expected. `2` is not a `E`
b[E::A]['\0'] = 42;
//b[E::A][2] = 42; // doesn't compile as expected. `2` is not a `char`
return 0;
}
Upvotes: 2
Reputation: 40145
It is impossible as it is because it is array elements of the same type.
struct s_i {
int i;
const wchar *wc[7];
};
struct s_e {
enum Ex e;
struct s_i i[6];
} ary[3];
Upvotes: 1
Reputation: 409166
No it's not possible.
What you can to is to make a class that behaves as an enumeration and has a subscript operator which returns another special class (that in general behaves as an int
) which has a subscript operator which in turn returns the wchar_t
array.
Upvotes: 0