4

我在我的项目中使用 boost 几何,我需要序列化多边形。对于许多 boost 数据类型,我一直在使用 boost 序列化而没有问题,但是 boost 几何似乎目前不支持序列化,因为我在序列化文件夹中找不到任何标题。

有没有众所周知的方法来实现这一目标?

谢谢。

编辑:二进制序列化示例:Boost Polygon Serialization: Ring

4

2 回答 2

3

我同意,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 添加序列化。在这里,我使用 Ring 和 Polygon 本质上分别是点和环的 std::vector(s) 的事实,并且 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);
}

享受!

于 2013-11-17T00:53:38.097 回答
1

Boost.Geometry 不支持 Boost.Serialization。您可以读写 WKT(众所周知的文本),这也是许多数据库使用的标准化 ASCII 格式。参见例如: http ://en.wikipedia.org/wiki/Well-known_text

还有 WKB(众所周知的二进制文件),但尚未 100% 支持。但是,对于多边形,它是受支持的。

于 2013-11-13T17:50:59.807 回答