我同意,奇怪的是 Boost.Geometry 不支持 Boost.Serialization。可能很难支持所有可能的模板参数组合,或者可能他们不关心,因为 WKT 已经提供了。
至少在“默认”容器类型的情况下,添加此类功能很简单。下面的代码实现了它并且功能齐全。
下面我假设您使用自定义类(来自 Qt 的 QPoint)作为点类。其他点类型的代码几乎与我的相同。
首先,为 Point 类添加序列化:
#include <QPoint>
#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/register/point.hpp>
BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET(QPoint, int, cs::cartesian, x, y, setX, setY);
typedef QPoint MyPoint;
namespace boost {
namespace serialization {
template<class Archive>
void serialize(Archive & ar, MyPoint& pt, const unsigned int version) {
ar & boost::serialization::make_nvp("x", pt.rx() );
ar & boost::serialization::make_nvp("y", pt.ry() );
}
} //namespace serialization
} //namespace boost
接下来,您将添加环和多边形的序列化。在这里,我使用了以下事实:Ring 和 Polygon 本质上分别是点和环的 std::vector,并且 std::vector 的序列化内置于 Boost.Serialization 中。
#include <boost/serialization/vector.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/ring.hpp>
//change template flags as you are pleased but ring and polygon has to be
//in correspondence w.r.t. to "closed" and "clockwise" policies
typedef boost::geometry::model::ring<MyPoint, false, true> MyRing;
typedef boost::geometry::model::polygon<MyPoint, false, true> MyPolygon;
namespace boost {
namespace serialization {
//Default ring<MyPoint> simply inherits from std::vector<MyPoint>,
//its serialization is trivial and no implementation is needed.
//Default polygon<MyPoint> gives direct access to outer ring and the container of inner rings
template<class Archive>
void serialize(Archive & ar, MyPolygon& poly, const unsigned int version) {
ar & boost::serialization::make_nvp("outer", poly.outer());
ar & boost::serialization::make_nvp("inners", poly.inners());
}
} //namespace serialization
} //namespace boost
就是这样,你已经完成了,现在你可以像任何其他类一样使用 MyPolygon 和 Boost.Serialize :
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
void foo_out(std::ostream & oss, const MyPolygon & poly)
{
boost::archive::xml_oarchive oa(oss);
oa & BOOST_SERIALIZATION_NVP(poly);
}
void foo_in(std::istream & iss, MyPolygon & poly)
{
boost::archive::xml_iarchive ia(iss);
ia & BOOST_SERIALIZATION_NVP(poly);
}
Enjoy!