【问题标题】:apply_visitor does not change objectapply_visitor 不改变对象
【发布时间】:2018-09-03 02:54:47
【问题描述】:

我继承自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);

    }
};

这个类应该改变一些对象的 x 和 y 位置,Point、Line 和 Circle。

当我执行以下代码时:

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` 之后没有改变?

【问题讨论】:

    标签: c++ c++11 boost-variant apply-visitor static-visitor


    【解决方案1】:

    您正在修改shape_variant,而不是pl

    试试

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 2018-03-08
      • 2014-08-18
      • 1970-01-01
      相关资源
      最近更新 更多