apply_visitor 不改变对象

apply_visitor does not change object

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

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);

    }
};

这个 class 应该改变一些对象,点,线和圆的 x 和 y 位置。

当我执行以下代码时:

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 保持为 1、2,l 也是如此。为什么我的对象在“apply_visitor”之后没有改变?

您正在修改 shape_variant,而不是 pl

尝试

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

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