2

我对将 boost::static_visitor 应用于变体和结构有点困惑。我在下面包含了一个测试用例。对于“s_visitor”中注释掉的部分,我不明白为什么会出现以下错误消息或如何修复它:

apply_visitor_unary.hpp:72:错误:“struct s1”没有名为“apply_visitor”的成员</p>

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

struct s1 {
  int val;

  s1(int a) : val(a) {}
};

struct s2 {
  s1  s;
  int val;

  s2(int a, int b) : s(a), val(b) {}
};

struct s_visitor : public boost::static_visitor<>
{
    void operator()(int & i) const
    {
        std::cout << "int" << std::endl;
    }

    void operator()(s1 & s) const
    {
        std::cout << "s1" << std::endl;
    }

    void operator()(s2 & s) const
    {
        std::cout << "s2" << std::endl;
        // -> following 'struct s1' has no member apply_visitor
        // boost::apply_visitor(s_visitor(), s.s);
        // -> following 'struct s1' has no member apply_visitor
        // boost::apply_visitor(*this, s.s);
        s_visitor v;
        v(s.s);
    }
};

int main(int argc, char **argv)
{
  boost::variant< int, s1, s2 > v;
  s1 a(1);
  s2 b(2, 3);

  v = a;
  boost::apply_visitor(s_visitor(), v);

  v = b;
  boost::apply_visitor(s_visitor(), v);

  return 0;
}

感谢您提供任何帮助和/或澄清。

4

1 回答 1

1

您会收到两条注释掉的行的编译错误,因为您传入了一个“s1”,其中需要一个 boost::variant。但是,在代码中,您知道确切的类型,因此您不需要进行变体访问,您可以使用类型 s1 的值做任何您想做的事情。

于 2011-04-28T20:31:27.897 回答