2

I am a bit confused on the application of boost::static_visitor for variants and structures. I have included a test case below. For the commented out sections in "s_visitor", I do not understand why the following error message occurs or how to fix it:

apply_visitor_unary.hpp:72: error: ‘struct s1’ has no member named ‘apply_visitor’

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

Thanks for any help and/or clarification.

dan10400
  • 23
  • 3

1 Answers1

1

You get compile errors for both of the commented-out lines because you are passing in an "s1" where a boost::variant is expected. At that point in the code, however, you know the exact type, so you don't need to do variant visitation, you can just do whatever you want with the value of type s1.

DataGraham
  • 1,625
  • 1
  • 16
  • 20
  • @dan10400 By the way, does the code "s_visitor v; v(s.s);" compile? I would think that it would, or alternatively I think "(*this)(s.s)" would work. – DataGraham Apr 28 '11 at 20:35
  • Thanks. This example was boiled down from a larger example where structs are mixed with variants and I think I was pushing for some integrated approach for walking the data structures. The code "s_visitor v; v(s.s);" does compile and work, because it uses the operator() for the type. This probably added to my confusion. The code "(*this)(s.s)" however, doesn't. – dan10400 Apr 29 '11 at 04:59