First of all let me say that I'm creating software for microcontrollers, so RAM usage matters and it makes sense to put large blocks of const data to non-volatile (flash) memory.
What I'm trying to achieve is to find a nice way to create a "split" object in C++. As an example let's assume that there's one byte of data (read/write) and a multibyte "receipt" for accessing it. Let's say that the "receipt" is a long string that is a filename, and the media that it points to is slow, so it makes sense to buffer the single byte in memory, instead of actually reading it on each request.
class Data
{
uint8_t byte;
bool valid;
const char filename[128];
uint8_t read()
{
if (!valid)
performReallySlowRead(filename, &byte);
valid = true;
return byte;
};
void write(uint8_t new_value)
{
byte = new_value;
performRealWriteToMedia(filename, byte);
valid = true;
};
}
The obvious problem with this approach is that whole 130-bytes end up in RAM, while only two of them need to be changed. So I've come up with an idea of split-object:
class DataNonConst
{
uint8_t byte;
bool valid;
}
class DataConst
{
const char filename[128];
DataNonConst * const data;
}
static DataNonConst storage;
const DataConst holder("some_long_name_here", &storage);
Now the only problem is that if I would like to have a few hundred of such split-objects the process of creating them (so creating TWO objects and linking second to first) gets pretty boring and problematic...
So the question is - is there some nice way to make it easier to use, preferably a clever-C++-trick or maybe some template magic? That is - how to create TWO objects, linked together, with a single statement, preferably one object is hidden? I don't think macro-solution is possible here, as there's no easy way to automate creation of the name