Re: Object (de)serialization
On Jan 25, 3:31 pm, Branimir Maksimovic <bm...@hotmail.com> wrote:
Thomas J. Gritzan wrote:
class Triangle : public Shape {
public:
Triangle() {
cerr << "ctor: Triangle\n";
}
static void registerClass() {
registerShape("triangle", &Shape::create<Triangle>);
}
};
int main()
{
Triangle::registerClass();
Shape *x = Shape::deserialise("triangle");
// checks if x has correct type:
cerr << typeid(*x).name() << endl;
delete x;
}
Perfect, I use this method since 1999.
Here's how I'd do it:
class SendCompressedBuffer;
class Counter;
class Shape {
public:
template <typename B>
explicit Shape(B* buf);
// Add virtual d'tor to allow delete through base pointer
virtual ~Shape() {}
virtual inline void
Send(SendCompressedBuffer* buf, bool = false) const;
virtual inline void
CalculateMarshallingSize(Counter&) const;
template <typename B>
static Shape* BuildPolyInstance(B* buf);
virtual void Draw() const =0;
};
class Triangle : public Shape {
public:
template <typename B>
explicit Triangle(B* buf);
virtual inline void
Send(SendCompressedBuffer* buf, bool = false) const;
virtual inline void
CalculateMarshallingSize(Counter&) const;
virtual void Draw();
};
The full output from the C++ Middleware Writer given the
above as input is here --
http://webEbenezer.net/posts/buildpoly.hh
And here's a portion of that output:
uint32_t const Shape_num = 7001;
uint32_t const Triangle_num = 7002;
template <typename B>
inline Shape*
Shape::BuildPolyInstance(B* buf)
{
uint32_t type_num;
buf->Give(type_num);
switch (type_num) {
case Triangle_num:
return new Triangle(buf);
default:
throw failure("Shape::BuildPolyInstance: Unknown type");
}
}
---------------------------------------------------------------
If there were other concrete, derived classes they would
be added to the switch statement. I think this is both
simpler and more complete than what has previously been
outlined -- there are Send/serialization functions and
the Draw method indicates Shape is an abstract class.
The automated generation of the type numbers helps to
conserve bandwidth. I don't recommend sending/receiving
class names as strings in a real application.
Brian Wood
http://webEbenezer.net
(651) 251-9384