在boost::geometry::for_each_point中使用lambda

Use lambda in the boost::geometry::for_each_point

本文关键字:lambda point each geometry for boost      更新时间:2023-10-16

我想将boost::model::polygon转换为boost::model::multi_point,下面是我的实现:

namespace bg = boost::geometry;
typedef bg::model::point<double, 3, bg::cs::cartesian> point3d;
bg::model::multi_point<point3d> result;
std::function<void(point3d)> appendPoint = [result](point3d point){
    bg::append(result, point);
};
bg::for_each_point(polygon, appendPoint);

但是这段代码给了我一个错误:

error: passing ‘boost::remove_reference<const boost::geometry::model::multi_point<boost::geometry::model::point<double, 3ul, boost::geometry::cs::cartesian> > >::type {aka const boost::geometry::model::multi_point<boost::geometry::model::point<double, 3ul, boost::geometry::cs::cartesian> >}’ as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = boost::geometry::model::point<double, 3ul, boost::geometry::cs::cartesian>; _Alloc = std::allocator<boost::geometry::model::point<double, 3ul, boost::geometry::cs::cartesian> >; std::vector<_Tp, _Alloc>::value_type = boost::geometry::model::point<double, 3ul, boost::geometry::cs::cartesian>]’ discards qualifiers [-fpermissive]

如果我理解正确的话,这类错误表明常量正确性存在问题。但是我真的不知道,这个关于const的代码有什么问题。有谁能告诉我,我的错误在哪里,如何补救?

问题是bg::append的第一个参数应该引用result,而result是通过lambda中的值捕获的。将捕获更改为

[&result](point3d point)

对于按值捕获,它报告关于const正确性的错误,因为您将临时对象作为参数传递,期望非const引用。