[IO library] Comment on the following c++ design

M

mathieu

Hello,

I am looking for suggestions on the following design (*). Basically
I am dealing with objects of type A, which can be serialized as 2
differents representations: B or C. I like this approach because B/C
can directly have access to the internal of A (which is required for
serialization). It also make it easy for user to add a new
representation D.

For the curious, I am writing a file format library and I am trying
to deal with third-party implementation bug. I know how to deal with
certain bugs, but they add a nonnegligable overhead if one is trying
to deal with them in the general case (B/C). Making them separate
classes make it easy for user to include/exclude them.

Thanks for comments,
-Mathieu

(*)
#include <iostream>

struct A
{
int a;
template <typename T>
void dump(std::eek:stream &os) {
static_cast<T&>(*this).dump(os);
}
};

struct B : public A
{
void dump(std::eek:stream& os) {
std::cout << "B:" << a << std::endl;
}
};

struct C : public A
{
void dump(std::eek:stream &os) {
std::cout << "C:" << a << std::endl;
}
};

int main()
{
A a = {2};
a.dump<B>(std::cout);
a.dump<C>(std::cout);
return 0;
}
 
A

Alexey Stepanyan

Hello,

struct B : public A
{
void dump(std::eek:stream& os) {
std::cout << "B:" << a << std::endl;
}

};

struct C : public A
{
void dump(std::eek:stream &os) {
std::cout << "C:" << a << std::endl;
}

};

1) i believe you meant os instead of std::cout here
2) as i understood you have several ways to format your class/struct A
so why not separate the formatting algorithm into the hierarchy
with
the following base class

class IFormatter
{
public:
virtual void Dump( std::eek:stream &os, const A& a ) = 0;
};

.....
This appears to be a simple Strategy Pattern

You should also add method to A which returns all information
which is necessary for serialization in some unified form
( perhaps an associate container "name"-"value" would fit )
this will preserve the incapsulation and decouple the formatting
algorithms from the internal representation of A. Thus you will be
able to modify formatting algorithms and A independently.
int main()
{
A a = {2};
a.dump<B>(std::cout);
a.dump<C>(std::cout);
return 0;
3) You should avoid casting A to B,C
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,148
Latest member
ElizbethDa
Top