Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2003-01-12 10:44:11


Ares Lagae <ares.lagae_at_[hidden]> writes:

> David Abrahams wrote:
>
>> I really don't agree with that part. Deserializing objects without
>> default constructors is just one example of something you can't do
>> easily just because you have reflection. Furthermore, any class with
>> decent encapsulation (e.g. private date members) might very well *not*
>> be easily adapted via introspection.
>
> well in fact both things can be done easilly (easilly does not mean clean OO coding) :
>
> /* represents a data member of a class */
> template <class C, typename T> /* class and data member type */
> class DataMember {
> public:
> /* construct from member data pointer and member data name (not used here) */
> DataMember(T C::*ptr, char * name) : m_ptr(ptr), m_name(0) {
> m_name = strdup(name);
> }
> ~DataMember() {
> free(m_name);
> }
> /* set the value of the data member */
> void setValue(C & instance, T value) {
> instance.*m_ptr = value;
> }
> /* get the value of the data member */
> T getValue() {
> return instance.*m_ptr;
> };
> private:
> T C::*m_ptr; /* data member pointer */
> char * m_name; /* data member name */
> };
>
> /* a global data member object */
> /* should be encapsulated in a class describing class Foo */
> class Foo;
> DataMember<Foo, int> * Foo_m_int;
>
> class Foo {
> public:
> Foo() {
> /* this is normally done by the describe method */
> /* m_int is private */
> Foo_m_int = new DataMember<Foo, int>(&Foo::m_int, "m_int");
>
> m_int = 3;
> }
> ~Foo() {
> printf("Foo::~Foo()\n");
> }
> void print() {
> printf("m_int = %d\n", m_int);
> }
> private:
> int m_int;
> };

If you're willing to intrude on the design of Foo, there are much
cleaner solutions using friend. However, non-intrusive serialization
should generally be possible even for classes which are
well-encapsulated.

-- 
                       David Abrahams
   dave_at_[hidden] * http://www.boost-consulting.com
Boost support, enhancements, training, and commercial distribution

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk