Rene gave a good answer. In addition to this, here is a complete example. Please note that I have added "custom conversion", i.e. operator T
to class proxy_T
.#include <iostream>
#include <array>
#include <stdexcept>
template <class T>
class myClass
{
std::array<T, 5> TheArray;
class proxy_T
{
T& value;
public:
proxy_T(T& v) : value(v) {}
proxy_T& operator=(T const& i)
{
if (i >= 0 and i <= 9)
{
value = i;
}
else
{
throw std::range_error(std::to_string(i));
}
return *this;
}
operator T()
{
return value;
}
};
public:
proxy_T operator [](int const idx)
{
return TheArray.at(idx);
}
T operator [](int const idx) const
{
return TheArray[idx];
}
};
int main() {
myClass<int> A;
std::cout << A[0] << std::endl;
A[0] = 2;
std::cout << A[0] << std::endl;
A[1] = 20;
}
Jonas source
share