boost :: apply_visitor不是[some]类的成员

时间:2012-10-06 23:46:54

标签: c++ boost operator-overloading visitor boost-variant

我有一个ShapeType,Point,有一些坐标,(1,2),我想在重载的operator()中使用apply_visitor将坐标(3,4)添加到我的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;
}

谢谢!

1 个答案:

答案 0 :(得分:3)

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

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

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

    你只想做

    myShape = myPoint;
    

    否则,如果该变体实际上还不包含Point,您将收到boost::bad_get例外

  3. 最后

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

    应该是

    boost::apply_visitor(ShapeVisitor(3,4), myShape);
    
  4. 显示所有这些点的简单自包含示例如下所示: (现场观看 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;
    }
    

    输出:

    4, 6