This works for pointers - not references. - the
following - along with compatible changes - should work.
Robert Ramey
void serialize(const base_class * src,
std::ostream& dest) {
boost::archive::binary_oarchive
oa(dest);
oa <<
BOOST_SERIALIZATION_NVP(src);
}
Hi,
I'm new to boost and I'm having some
trouble serializing an object using a reference to its base
class.
Although there are a lot of messages related to this topic in
the newsgroups and the doc, I did not find a workable answer to my proplem.
In the following code, the function serialize takes a reference to
base_class as parameter. But the serialize method of derived_class is never
called.
Did I miss something ?
Thanks for your
help
Marc
#include <string>
#include
<sstream>
#include <iostream>
#include
<boost/archive/binary_oarchive.hpp>
#include
<boost/archive/binary_iarchive.hpp>
#include
<boost/serialization/string.hpp>
#include
<boost/serialization/access.hpp>
#include
<boost/serialization/is_abstract.hpp>
#include
<boost/serialization/export.hpp>
using namespace
std;
class base_class {
friend class
boost::serialization::access;
public:
base_class() :
my_string("") { };
base_class(string s) : my_string(s) {
};
virtual ~base_class()
{};
virtual void foo(void) =
0;
template<class
Archive>
void
serialize(Archive & ar, const unsigned int
version)
{
ar
&
BOOST_SERIALIZATION_NVP(my_string);
}
public:
string
my_string;
};
BOOST_IS_ABSTRACT(base_class);
BOOST_CLASS_EXPORT(base_class);
class
derived_class : public base_class {
friend class
boost::serialization::access;
public:
derived_class() :
base_class(), my_int(0) {};
derived_class(string s, int i) : base_class(s), my_int(i)
{};
virtual ~derived_class()
{};
void foo(void)
{};
template<class
Archive>
void
serialize(Archive & ar, const unsigned int
version)
{
ar
&
BOOST_SERIALIZATION_BASE_OBJECT_NVP(base_class)
&
BOOST_SERIALIZATION_NVP(my_int);
}
int
my_int;
};
BOOST_CLASS_EXPORT(derived_class);
void
serialize(const base_class& src, std::ostream& dest)
{
boost::archive::binary_oarchive
oa(dest);
oa <<
BOOST_SERIALIZATION_NVP(src);
}
int main(int argc, char** argv)
{
try {
std::stringstream ss;
derived_class d("aaa", 5);
cout
<< "before: " << d.my_string << " " << d.my_int
<< endl;
serialize(d,
ss);
//
deserialize
derived_class
d2;
boost::archive::binary_iarchive
ia(ss);
ia >>
d2;
cout << "after: "
<< d2.my_string << " " << d2.my_int <<
endl;
}
catch (const
std::exception& ex) {
cout
<< "std exception: " << ex.what() <<
endl; }
catch (...)
{
cout << "unknown
exception" << endl;
}
}
Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great
rates starting at 1¢/min.
_______________________________________________
Boost-users mailing
list
Boost-users@lists.boost.org
http://lists.boost.org/mailman/listinfo.cgi/boost-users