代码之家  ›  专栏  ›  技术社区  ›  Mutating Algorithm

apply\u visitor不更改对象

  •  0
  • Mutating Algorithm  · 技术社区  · 6 年前

    我继承了 boost::static_visitor<> 并定义了一个类如下:

    class move_visitor : public boost::static_visitor<> {
    
    private:
    
        double m_dx, m_dy;
    
    public:
    
        move_visitor() : m_dx(0.0), m_dy(0.0) {}
        move_visitor(double dx, double dy) : m_dx(dx), m_dy(dy) {}
        ~move_visitor() {}
    
        void operator () (Point &p) const {
            p.X(p.X() + m_dx);
            p.Y(p.Y() + m_dy);
        }
    
        void operator () (Circle &c) const {
    
            Point center_point(c.CentrePoint().X() + m_dx, c.CentrePoint().Y() + m_dy);
            c.CentrePoint(center_point);
        }
    
        void operator() (Line &l) const {
            Point start(l.Start().X() + m_dx, l.Start().Y() + m_dy),
                end(l.End().X() + m_dx, l.End().Y() + m_dy);
    
            l.Start(start);
            l.End(end);
    
        }
    };
    

    当我执行以下代码时:

    int main()
    {
    
    typedef boost::variant<Point, Line, Circle> ShapeType;
    
    Point p(1, 2);
    Line l(p, p);
    Circle c(p, 5);
    
    ShapeType shape_variant;
    
    std::cout << p << "\n\n"
              << l << "\n\n" 
              << c << "\n\n";
    
    shape_variant = p;
    boost::apply_visitor(move_visitor(2, 2), shape_variant);
    
    std::cout << p << std::endl;
    
    shape_variant = l;
    boost::apply_visitor(move_visitor(2, 2), shape_variant);
    std::cout << std::endl << l << std::endl;
    
    return 0;
    }
    

    p l

    1 回复  |  直到 6 年前
        1
  •  2
  •   molbdnilo    6 年前

    你在修改 shape_variant ,不是 p l .

    std::cout << boost::get<Point>(shape_variant) << std::endl;
    

    std::cout << boost::get<Line>(shape_variant) << std::endl;
    
    推荐文章