gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:59:38 27 4
gpt4 key购买 nike

我有一个 ShapeType 点,带有一些坐标 (1,2),我想在重载运算符 () 中使用 apply_visitor 将坐标 (3,4) 添加到我的点,这样点最终是 (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. 您缺少包含(编辑:似乎不再需要)

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

显示所有这些要点的一个简单的独立示例如下所示:(在 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

关于c++ - boost::apply_visitor 不是 [some] 类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12764868/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com