Boost logo

Boost :

From: Jonathan Turkanis (technews_at_[hidden])
Date: 2004-09-29 12:23:58


"Vladimir Prus" <ghost_at_[hidden]> wrote in message
news:cje34t$f10$1_at_sea.gmane.org...
> Jonathan Turkanis wrote:

> >> template<class>
> >> figure_out_name_offset
> >> {
> >> figure_out_name_offset operator&(nvp& p)
> >> {
> >> if (p.name() == "name")
> >> {
> >> m_address = &p.value()
> >> }
> >> }
> >> std::string* m_address;
> >> };
> >> Person p;
> >> figure_out_name_offset f;
> >> p.serialize(f);
> >> unsigned offset = (int)f.m_address - (int)&p;
> >
> > Does this force the class to represent it's fields as strings?
>
> The above code -- yes, but I've used std::string for simplicity. I think
> it's possible to modify the example in such a way that you won't store an
> address of a variable but a formatter*, created from using address of
> object, address of &p.value() and depending on type of p.value()

The problem is that user-defined types have to be given a way to announce the
static types of their subelements, or that information will be lost and can't be
used by the formatting objects with templated member functions. With
serialization, everything work (putting aside pointers to polymorphic objects)
because the class itself manages its own deserialization and so knows the static
types.

For example, suppose you pass an archive object of some sort, with an overloaded
operator& (I'd rather use operator<<), to the format member function of a
user-defined type:

    struct Dog {
        template<typename FormatHelper>
        void format(FormatHelper& fmt)
        {
             fmt & name;
             fmt & weight;
        }
        std::string name;
        float weight;
    };

Here, fmt knows the type of the member field name only during the execution of
fmt & name. If it wants to format weight first, it has no way to store the name,
unless Dog tell it, independently, that its fields have type (string, float).
Then fmt can allocate a tuple<string, float> to store the values. This is still
wasteful if fmt only wants to use the second field.

Maybe I am overlooking some implementation technique.

Jonathan


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