Similar questions have already been asked several times, but they asked me to create a new topic, and not engage in necromancy))). Actually, here is a very related topic: C++ [] array operator with multiple arguments?
But this solution came to my mind:
struct TIndex {
size_t value;
TIndex() : value(0) {};
TIndex(size_t value) : value(value) {};
operator size_t () const { return value; };
operator size_t& () { return value; };
};
struct TSubscript_2D {
TIndex x;
TIndex y;
TSubscript_2D() : x(0), y(0) {};
TSubscript_2D(TIndex x, TIndex y) : x(x), y(y) {};
TSubscript_2D(TIndex x) : x(x), y(0) {};
};
TSubscript_2D&& operator, (const TIndex& x, const TIndex& y) {
return TSubscript_2D(x, y);
};
struct TMatrix_2D {
size_t width;
size_t height;
std::vector<int> content;
TMatrix_2D(size_t width, size_t height) : width(width), height(height), content(width* height) {};
int& operator [](TSubscript_2D subscr) {
return content[(width * subscr.y) + subscr.x];
};
const int& operator [](TSubscript_2D subscr) const {
return content[(width * subscr.y) + subscr.x];
};
};
int main()
{
setlocale(LC_ALL, "");
TIndex x = 1, y = 2;
TMatrix_2D mmm (5, 5);
mmm[x, y] = 3; // content[5*2 + 1] = content[11] = 3
mmm[0, y] = 5; // content[5*2 + 0] = content[10] = 5
mmm[x, 1] = 7; // content[5*1 + 1] = content[6] = 7
std::vector<int> vvv = { 5,4,3,2,1 };
vvv[x] = 5;
...
Please tell a beginner how viable this approach to solving this problem is.
Of course, all this can be covered with templates and macrasses, but the question is the viability of the principle itself - create a separate class for indexing.
Oh, elso, all this matters for versions below C++23, of course.