我已经阅读了大量类似的问题,但没有找到答案。我正在使用 Visual Studio 2010 和 boost 1.47。
这是代码,它是完整且可编译的:
#include "stdafx.h"
#include <string>
#include <sstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
using namespace std;
class BaseObject
{
public:
BaseObject(void) { };
virtual ~BaseObject(void) { };
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{ /* nothing happens here */ };
};
class DerivedObject : public BaseObject
{
public:
string text;
public:
DerivedObject(void) { };
~DerivedObject(void) { };
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & text;
};
};
BOOST_CLASS_EXPORT(DerivedObject)
int _tmain(int argc, _TCHAR* argv[])
{
DerivedObject der;
der.text = "Testing!";
std::ostringstream os;
boost::archive::text_oarchive oa(os);
oa.register_type<DerivedObject>();
// I made a DerivedObject, but I'm casting it to a BaseObject
// as the serialization code should not have to know what type it is
BaseObject *base = &der;
// now serialize it
oa << *base;
printf("serialized: %s\r\n",os.str().c_str());
return (0);
}
你可以看到它真的很简单,我已经添加了 BOOST_CLASS_EXPORT 和 oa.register_type 魔法,它应该确保 DerivdObject::serialize() 被调用,即使它不是虚拟方法.. 但仍然只有 serialize() 在BaseObject 被调用。可能是 Visual C++ 特有的问题?请指教?