You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Boost Geometry注册2D Node结构体时出现只读位置赋值错误

问题原因分析

你的编译错误源于BOOST_GEOMETRY_REGISTER_POINT_2D宏的使用方式:当你用p.pos.get<0>()作为坐标访问表达式时,Boost Geometry自动生成的set函数会尝试直接给get<0>()的返回值赋值。但在部分Boost版本或编译器解析逻辑中,get<N>()成员函数会被解析为const重载,导致返回值是只读引用,无法完成赋值操作。

解决方案

方案一:改用Boost Geometry自由函数注册坐标

将注册宏中的坐标访问表达式替换为Boost Geometry提供的自由函数get<N>(),它会自动适配非const对象的可写访问:

// 你的自定义Node结构体
struct Node {
    boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> pos;
    unsigned int id;
};

// 替换原注册宏
BOOST_GEOMETRY_REGISTER_POINT_2D(
    Node,
    double,
    boost::geometry::cs::cartesian,
    boost::geometry::get<0>(p.pos),
    boost::geometry::get<1>(p.pos)
)

方案二:手动特化Boost Geometry Traits(更可靠)

直接手动特化几何类型的traits,明确控制坐标的读写逻辑,完全规避宏定义带来的潜在问题:

struct Node {
    boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian> pos;
    unsigned int id;
};

namespace boost { namespace geometry { namespace traits {

// 标记Node为点类型
template<> struct tag<Node> { typedef point_tag type; };
// 定义坐标类型
template<> struct coordinate_type<Node> { typedef double type; };
// 定义坐标系
template<> struct coordinate_system<Node> { typedef cs::cartesian type; };
// 定义维度为2D
template<> struct dimension<Node> : boost::mpl::int_<2> {};

// 实现X坐标的读写
template<> struct access<Node, 0> {
    static inline double get(const Node& n) {
        return get<0>(n.pos);
    }
    static inline void set(Node& n, double value) {
        set<0>(n.pos, value);
    }
};

// 实现Y坐标的读写
template<> struct access<Node, 1> {
    static inline double get(const Node& n) {
        return get<1>(n.pos);
    }
    static inline void set(Node& n, double value) {
        set<1>(n.pos, value);
    }
};

}}} // namespace boost::geometry::traits

这种方式直接调用Boost Geometry提供的set<N>函数修改坐标,完全符合库的设计规范,不会出现只读引用赋值的问题。

内容的提问来源于stack exchange,提问作者Computer Crafter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 18:49:11