1

我有一个 ShapeType,Point,有一些坐标,(1,2),我想在重载运算符 () 中使用 apply_visitor 将坐标 (3,4) 添加到我的 Point,因此 Point 最终成为(4,6)。我的实施在哪里失败?我认为我的 ShapeVisitor 类是正确的,但我收到一个错误,“apply_visitor”不是 CLARK::Point 的成员。

代码如下。

#include "Point_H.hpp"
#include "Shape_H.hpp"
#include "boost/variant.hpp"

typedef boost::variant<Point,Line,Circle> ShapeType;

ShapeType ShapeVariant(){...}

class ShapeVisitor : public boost::static_visitor<> 
{
private:
    double m_dx; // point x coord
    double m_dy; // point y coord

public:    
    ShapeVisitor(double m_dx, double m_dy);
    ~ShapeVisitor();

    // visit a point
    void operator () (Point& p) const
    {
        p.X(p.X() + m_dx);
        p.Y(p.Y() + m_dy);
    }
};

int main()
{   
    using boost::variant;

    ShapeType myShape = ShapeVariant(); // select a Point shape

    Point myPoint(1,2);

    boost::get<Point>(myShape) = myPoint; // assign the point to myShape

    boost::apply_visitor(ShapeVisitor(3,4), myPoint); // trying to add (3,4) to myShape

    cout << myPoint << endl;

    return 0;
}

谢谢!

4

1 回答 1

3
  1. 您缺少包含(编辑:似乎不再需要)

    #include "boost/variant/static_visitor.hpp"
    
  2. 也代替

    boost::get<Point>(myShape) = myPoint;
    

    你只想做

    myShape = myPoint;
    

    否则,如果变体实际上还没有包含 a Point,您将收到boost::bad_get异常

  3. 最后

    boost::apply_visitor(ShapeVisitor(3,4), myPoint);
    

    本来应该

    boost::apply_visitor(ShapeVisitor(3,4), myShape);
    

A simple self-contained example that shows all these points would look like this: (See it live on http://liveworkspace.org/code/33322decb5e6aa2448ad0359c3905e9d)

#include "boost/variant.hpp"
#include "boost/variant/static_visitor.hpp"

struct Point { int X,Y; };

typedef boost::variant<int,Point> ShapeType;

class ShapeVisitor : public boost::static_visitor<> 
{
private:
    double m_dx; // point x coord
    double m_dy; // point y coord

public:    
    ShapeVisitor(double m_dx, double m_dy) : m_dx(m_dx), m_dy(m_dy) { }

    void operator () (int& p) const { }

    // visit a point
    void operator () (Point& p) const
    {
        p.X += m_dx;
        p.Y += m_dy;
    }
};

int main()
{   
    Point myPoint{ 1,2 };

    ShapeType myShape(myPoint);
    boost::apply_visitor(ShapeVisitor(3,4), myShape);

    myPoint = boost::get<Point>(myShape);
    std::cout << myPoint.X << ", " << myPoint.Y << std::endl;
}

Output:

4, 6
于 2012-10-06T23:50:17.053 回答