Currently I’m trying to implement some kind of object stream, similar to the structure that exists in java.
Using the “Stream Socket API” by Rob Tougher it’s easy to use the stream insertion operator<<.
This would lead to the problem that every serializable object would require every single class to overload the same operators in the same manner.
Example:
class A
{
protected:
int value;
friend ostream& operator <<( ostream& in, const A& obj );
};
class B
{
protected:
float value;
friend ostream& operator <<( ostream& in, const B& obj );
};
ofstream& operator<< (ofstream& in, const A& obj)
{
return (in << obj.value);
}
ofstream& operator<< (ofstream& in, const B& obj)
{
return (in << obj.value);
}
Well. That’s easy and works. Now I’m thinking about whether it’s somehow possible to ease and automate the process of this serialization.
I already thought back and forth how this could be done using some combination with both, templates and macros. Using typeid (RTTI) would partially work, but this fails at the point where you would need to cast a value in a type when only the typeid is known. Which simply isn’t possible.
Is there really no other solution that to simply let the user implement each and every operator<< ? Am I thinking too far and the solution is quite easy?
Otherwise, in all ways I’ve tried and thought through, the problem ends at where I need to reinstanciate an object when the classname isn’t known at compile-time.
Any idea is appreciated.
PS: Using fwrite(item, sizeof(item), 1, handle); isn’t the solution as well. Not platform independent at all.
Java serialization relies on reflection to automatically discover and serialize class fields. In C++, your options are: