I'm trying to build a wrapper class for static array, which should behave like a standard static array.
int main()
{
int t[2][3] = {{77, 2, 3}, {4, 5, 6}};
auto a = make_array(t);
auto b = a[0]; // gives a ArrayWrapper<int, 3>
auto c = b[0]; // gives an int of value 77;
return 0;
}
So far I've written the following class and construction function:
#include <cstdlib>
template <typename T, size_t N>
struct ArrayWrapper;
template<typename T, size_t N>
auto make_array(T const (&tab) [N])
{
return ArrayWrapper<T, N>(tab);
}
template <typename T, size_t N>
struct ArrayWrapper
{
ArrayWrapper(T const (&tab)[N])
: t(tab)
{
}
template<typename U, size_t M>
ArrayWrapper<U, M> operator[] (size_t i)
{
return make_array<U, M>(t[i]);
}
T const & t;
};
Unfortunately, during the affectation of b
g++ gives me the following error:
error: no match for ‘operator[]’ (operand types are ‘ArrayPrinter<int [3], 2>’ and ‘int’)
auto b = a[0];
Plus I don't know how to specialize the [] operator
to return a basic type when ArrayWrapper
just contains has one dimension. I'm guessing I should specialize the operator when T is not an array but I could not make it compile.
Can anyone tell me how to help g++ make the template deduction for the [] operator when T is an array?
Can anyone tell me how to tell the [] operator to return the basic type when T is not an array anymore?