With C++ operator overloads, it is possible to create a class which emulates a pointer type, so I was experimenting with abstracting FILE
read operations with this approach.
class FilePointer
{
FILE* file;
size_t position;
FilePointer (FILE* file, size_t position)
{
this->file = file;
this->position = position;
};
public:
FilePointer (FILE* file)
{
this->file = file;
this->position = 0;
};
FilePointer operator+ (size_t offset)
{
return FilePointer(file,position + offset);
};
FilePointer operator++ () // Prefix : ++FilePointer
{
position++;
return *this;
};
FilePointer operator++ (int) // Postfix : FilePointer++
{
FilePointer before = *this;
position++;
return before;
};
FilePointer operator+= (size_t offset)
{
position += offset;
return *this;
};
uint8_t operator* ()
{
fseek(file,position,SEEK_SET);
Uint8 out;
fread(&out,1,1,file);
return out;
};
uint8_t operator[] (size_t offset)
{
return *(*this + offset);
};
};
As can be seen in the above code snippet I was able to find out how to differentiate between the variations of increment operator so that given FilePointer f;
f++
and ++f
would behave intuitively.
What if I want to use this class for file writes, though? Currently I can grab a byte uint8_t something = f[0];
and it works, but if I want to "set" something, i.e. f[0] = 100;
, the overloads as they are will not work for this.
Aside from whether or not this is "good practice" (though feel free to weigh in about that too), is there a way to implement this behavior in operator overloads for a class?
uint8_t n = f[0];
n++;
f[0] = n;
Or, getting even fancier, something like this:
f[1]++;
One way I imagine it could be done is by implementing yet another class which represents a "dereferenced FilePointer", but was curious if it is possible to do with only the overloads in the FilePointer class itself.