Boost logo

Boost :

Subject: Re: [boost] [serialization] how to serialize map ofnon-default-constructible?
From: Chard (boost_at_[hidden])
Date: 2009-11-24 18:29:05


<ivo.t_at_[hidden]> wrote in message
news:ECB13B9D09204914A385D25B334DF831_at_Ivo2...
> Hi to everybody,
>
> I'm new to the list, work for some time with Boost and C++ and have a
>
> fair knowledge but am not an expert yet. I try to serialize a map whose
> type

This is really a question for the boost users group, but...

> ist not default-constructible, and I'm seriously stuck there. I thought
> the
> load_construct_data and save_construct_data overrides would help me there,
> but that seems not to be the case. I tried to create a private default
> constructor hoping that the map (respectively pair) constructor could
> access

This is because boost::serialization does not put any special handling in
for std::pair when serialized via std::map.

It is the default construction of the pair that trips you up.

> it, due to the boost::serialization::access friend declaration, but that
> didn't work as well. I really do _not_ want to make a public default
> constructor. What could I do as a workaround??

You could specialize the construct_data functions for the pair (i.e. the
map's value_type), e.g.:

////////
// Example, non-default constructable class
class X
{
public:
    X(int i) : i_(i) {}

private:
    int i_;
    friend class boost::serialization::access;
    template <typename A>
    void serialize(A &ar, const unsigned)
    {
        ar & i_;
    }
};

template <typename A>
inline void load_construct_data(A &ar, X * x, const unsigned)
{
    ::new(x)X(1); // e.g.
}
////////

typedef std::map<int, X> Map;
typedef Map::value_type PairType;

template <typename A>
inline void serialize(A &ar, PairType &p, const unsigned)
{
    // Do nothing, handled by xxxx_construct_data
}

template <typename A>
inline void save_construct_data(A &ar, const PairType *p, const unsigned v)
{
    using namespace boost::serialization;
    ar << make_nvp("first", p->first);
    save_construct_data(ar, &p->first, v);
    ar << make_nvp("second", p->second);
    save_construct_data(ar, &p->second, v);
}

template <typename A>
inline void load_construct_data(A &ar, PairType *p, const unsigned v)
{
    using namespace boost::serialization;
    typedef BOOST_DEDUCED_TYPENAME
boost::remove_const<PairType::first_type>::type typef;
    load_construct_data(ar, &const_cast<typef &>(p->first), v);
    ar >> make_nvp("first", const_cast<typef &>(p->first));

    load_construct_data(ar, &p->second, v);
    ar >> make_nvp("second", p->second);
}


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