Boost logo

Boost :

From: Ares Lagae (ares.lagae_at_[hidden])
Date: 2003-01-12 09:52:27


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;
};

void main() {

        // setting private data members
        Foo foo;
        foo.print(); /* prints 3 */
        Foo_m_int->setValue(foo, 8);
        foo.print(); /* prints 8 */

        // unserializing withouth default constructor
        Foo * foo2 = (Foo *) malloc(sizeof(Foo)); /* no constructor called */
        foo2->print(); /* prints bullshit */
        Foo_m_int->setValue((*foo2), 8);
        foo2->print(); /* prints 8 */
        delete foo2; /* destructor called */ /* malloc - delete is not legal i guess */
}

best regards,
Ares Lagae


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