Re: Question on private virtual methods
On 18/07/2012 01:02, plegdfmds@gmail.com wrote:
Hi everyone,
I have a question on how to structure some private virtual methods.
MY problem is: I have some classes I need to serialize on a vector of bytes to be transmitted (and then reconstructed on the other end). What I want to do is having a class "Serializable" (inherited by all serializable classes) that specifies the interface of the (de)serialization mechanism, while the implementation is left to some private virtual methods that the derived classes need to implement. For example, for a class A:
class Serializable
{
public:
Bytestream serialize();
void deserialize(Bytestream&);
private:
virtual Bytestream serializeStep1() = 0;
virtual void deserializeStep1(Bytestream&) = 0;
};
Bytestream Serializable::serialize() {
return serializeStep1();
}
void Serializable::deserialize(Bytestream&) {
deserializeStep1(Bytestream&);
}
class A: public Serializable
{
private:
virtual Bytestream serializeStep1();
virtual void deserializeStep1(Bytestream&);
};
and A implements serializeStep1 e deserializeStep1 depending on its internal members.
Now, my problem is: class A is itself inherited by classes B!, B2 etc. I'd like to build a "cascaded serialization": in the serialization of B1, first A is serialized and then the internals of B1 are serialized and appended to the Bytestream.
How to do this? The only thing I can think of is a cascade of private methods like this:
class A: public Serializable
{
private:
virtual Bytestream serializeStep1();
virtual Bytestream serializeStep2() = 0;
virtual void deserializeStep1(Bytestream&);
virtual void deserializeStep2(Bytestream&) = 0;
};
Bytestream A::serialize() {
return serializeStep1() + serializeStep2(); // il '+' concatena
}
void A::deserialize(Bytestream&) {
deserializeStep1(Bytestream&);
deserializeStep2(Bytestream&);
}
class B1: public A
{
private:
virtual Bytestream serializeStep2();
virtual void deserializeStep2(Bytestream&);
}
but it doesn't look good, because now I need to structure A differently depending whether it's inherited or not.
How to do this?
I use something like the following to handle serialization:
struct i_stream
{
// functions to encode/decode types to/from a stream ...
};
struct i_serializable
{
virtual void deserialize(const i_stream& p) = 0;
virtual void serialize(i_stream& p) = 0;
};
struct foo : i_serializable
{
foo() {}
foo(const i_stream& p) { deserialize(p); }
virtual void deserialize(const i_stream& p) { p >> a; p >> b; }
virtual void serialize(i_stream& p) { p << a; p << b; }
int a;
std::string b;
};
struct bar : foo
{
bar() {}
bar(const i_stream& p) : foo() { deserialize(p); }
virtual void deserialize(const i_stream& p) { foo::deserialize(p); p >>
c; p >> d; }
virtual void serialize(i_stream& p) { foo::serialize(p); p << c; p << d; }
int c;
std::string d;
};
Works quite well.
/Leigh