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.
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.