Hello!
Suppose I'm writing a library to write a binary representation
of some data to a stream. Let's say that to make it extensible
in the future I'm preceding the actual data with some info
like the number of fields, total length, etc. that make up
some kind of header, assuming the actual data may change
over time.
I was hoping to implement a 'class datafile' that would
represent the whole datafile, a 'class record' which would
consist of a header and the actual data. I want the 'record'
class to have a member to write it to a stream, like
record::write(ostream &out) {
// write record number
// write other stuff like sizeof(actual_data)
// write actual_data
}
I was aiming for a design that would allow the class
actual_data to vary, ie. NOT be defined in the library
I'm writing, but be defined in the program that uses
the library. Then I would write programs that would
define their own actual_data class and use the library
to store records into a datafile.
To make the library independent of actual_data I
have decided to only store a pointer to it, so the
record class would look like this
class record {
// some header data
actual_data *content;
}
Now, it turns out that if actual_data is non-POD then
I must provide some means to serialize it, like overloading
<< and >> or providing some save_to_bytes()/restore_from_bytes()
members. These would be used in record::write during
'write actual_data'. Of course these would have to be supplied
by the program using the library, as they depend on the precise
content of actual_data.
The problem is -- how do I convince the library that I can
call these functions using -> on the pointer to actual_data?
Obviously the library doesn't know what actual_data looks like...
So is there any way to tell the compiler "OK, I have a class
called actual_data that has some fields you don't know in
advance, so I can't give you a definition yet, but it definitely
has some get/put methods so you'll know how to store and restore
it?"
It would also be useful if actual_data could pass some info
to the library, like a 'my_size()' member function, but the
same problem occurs.
So how do I tell the compiler that I have a class that supports
some interface without revealing the whole class definition?
thanks in advance,
- J.