如何用boost::serialization去序列化派生模板类

本篇是boost::serialization 用基类指针转存派生类(错误多多。一波三折)的姊妹篇。这里仅仅只是做一个总结。


先来看一个基类

class base_class
{
public:
	base_class(int m=0) : base_member_(0) {}
	virtual ~base_class() {}

	virtual void print_data() = 0;
protected:
	int base_member_;
	//other member...
};
它的一个模板派生类

template<typename T>
class divided_class : public base_class
{
public:
	divided_class(int m = 0, T d = T()) : base_class(m), diveded_member_(d) {}
	virtual ~divided_class() {}

protected:
	T diveded_member_;
	//other member....
};
如今我们来看如何用boost::serialization来序列化模板类
1.首先我们用一个宏来告诉boost base_class是一个抽象类:

BOOST_SERIALIZATION_ASSUME_ABSTRACT(base_class);
2.分别在基类和派生了中定义序列化函数
基类的序列化函数:

private:
	class boost::serialization::access;
	template<typename Archive>
	void serialize(Archive & ar, const unsigned int file_version)
	{
		ar & BOOST_SERIALIZATION_NVP(base_member_);
		//ar & BOOST_SERIALIZATION_NVP(other member...);
	}
这个序列化函数为什么是私有的,请自己看boost文档
模板派生类的序列化函数为:

private:
	class boost::serialization::access;
	template<typename Archive>
	void serialize(Archive & ar, const unsigned int file_version)
	{
		ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(base_class);//这个地方直接用ar & boost::serialization::base_object<base_class>(*this)会出错
		ar & BOOST_SERIALIZATION_NVP(diveded_member_);
		//ar & BOOST_SERIALIZATION_NVP(other member...);
	}
3.在save中注冊派生模板类

void save()
{
	std::ofstream ofs("t8.xml");
	boost::archive::xml_oarchive oa(ofs);

	base_class* int_base = new divided_class<int>(1, 3);
	base_class* str_base = new divided_class<std::string>(1, "wyp");
	base_class* float_base = new divided_class<float>(1, 3.1415926f);

	//Now the tricky point is to register class in serialize
	oa.template register_type<divided_class<int>>(NULL);
	oa.template register_type<divided_class<std::string>>(NULL);
	oa.template register_type<divided_class<float>>(NULL);

	//begin serialize
	oa & BOOST_SERIALIZATION_NVP(int_base);
	oa & BOOST_SERIALIZATION_NVP(str_base);
	oa & BOOST_SERIALIZATION_NVP(float_base);
}
4.在load中相同也要注冊派生模板类。并且要和save中注冊的一样

void load()
{
	std::ifstream ifs("t8.xml");
	boost::archive::xml_iarchive ia(ifs);

	base_class* int_base;
	base_class* str_base;
	base_class* float_base;

	//Now the tricky point is to register class in serialize
	ia.template register_type<divided_class<int>>(NULL);
	ia.template register_type<divided_class<std::string>>(NULL);
	ia.template register_type<divided_class<float>>(NULL);

	//begin serialize
	ia & BOOST_SERIALIZATION_NVP(int_base);
	ia & BOOST_SERIALIZATION_NVP(str_base);
	ia & BOOST_SERIALIZATION_NVP(float_base);

	//do something...
	int_base->print_data();std::cout << std::endl;
	str_base->print_data();std::cout << std::endl;
	float_base->print_data();std::cout << std::endl;
}
基本上就这几步。!

。!







原文地址:https://www.cnblogs.com/mqxnongmin/p/10939266.html