Boost logo

Boost Users :

Subject: Re: [Boost-users] [serialization] Serializing derived template classvia base pointer
From: Daniel Mitchell (dlm.bulk.messages_at_[hidden])
Date: 2013-01-17 23:52:27


On Jan 17, 2013, at 4:29 PM, Tim Moore <tim_at_[hidden]> wrote:

> On 2013-01-17 16:35, Daniel Mitchell wrote:
>
> I don't totally understand your original issue, but does this possibly do what you are wanting ??
>
> #include <fstream>
> #include <boost/archive/binary_oarchive.hpp>
> #include <boost/archive/binary_iarchive.hpp>
> #include <boost/serialization/access.hpp>
> #include <boost/serialization/export.hpp>
>
> struct base {
> template<typename Archive>
> void serialize(Archive& ar, unsigned version) { }
>
> virtual ~base() { }
> };
>
> BOOST_CLASS_EXPORT_KEY(base);
> BOOST_CLASS_EXPORT_IMPLEMENT(base);
>
> template<typename T>
> struct derived : base {
> derived() { }
> derived(int v) : data(v) { }
>
> template<typename Archive>
> void serialize(Archive& ar, unsigned version) {
> ar & boost::serialization::base_object<base>(*this);
> ar & data;
> }
>
> T data;
> };
>
> BOOST_CLASS_EXPORT_KEY(derived<int>);
> BOOST_CLASS_EXPORT_IMPLEMENT(derived<int>);
>
>
> int main() {
> base* b = new derived<int>(99);
> std::ofstream o("test.out", std::ios::binary);
> if (o.good()) {
> boost::archive::binary_oarchive oa(o);
> oa & b;
> }
> o.close();
> delete b;
>
>
> std::ifstream i("test.out", std::ios::binary);
> if (i.good()) {
> base* b;
> boost::archive::binary_iarchive ia(i);
> ia & b;
> std::cout << static_cast<derived<int>*>(b)->data << std::endl;
> }
> i.close();
> }

Hi Tim, thanks for your reply. I don't think that works for my purposes. The classes base and derived<T> are library implementation details. The type T is supplied by library users (this what I meant when I said it was an unknown type--it is unknown to me, the library author). Although I could require users to "register" their types in the way you suggest, it is very unappealing to do so, just as it would be very unappealing if the STL required types to be "registered" before they could be used in containers. That's not the kind of design I want to pursue. I don't want to impose any additional burdens on my users other than making their own types serializable (these types become the T in derived<T>).

In case more context would help, look at the type object_t here:

https://github.com/boostcon/cppnow_presentations_2012/blob/master/fri/value_semantics/value_semantics.cpp

Basically that's the class I want to serialize. I have a container of these things and I want to use them with boost.mpi. The nested classes concept_t and model<T> correspond to base and derived<T>. The type T is the user supplied type.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net