首次使用Boost,并尝试了解如何使用boost::variant
。请在下面找到示例程序和错误消息(GCC v5.3.0,-std = c ++ 14)
#include <vector>
#include <iostream>
#include <sstream>
#include <boost/variant.hpp>
using int_tree_t =
boost::make_recursive_variant <
int,
std::vector<boost::recursive_variant_>>;
auto operator << (std::ostream& out, const int_tree_t& tree) ->
std::ostream&
{
struct stringify :
public boost::static_visitor <std::string>
{
public:
auto operator () (int i) const ->
std::string
{
return std::to_string (i);
}
auto operator () (const std::vector<int_tree_t>& vec) const ->
std::string
{
std::stringstream ss;
ss << "(";
auto it = std::begin (vec);
if (!vec.empty ()) {
ss << *it;
}
for (; it != std::end (vec); ++it) {
ss << " " << *it;
}
ss << ")";
return ss.str ();
}
};
std::stringstream ss;
ss.flags (out.flags ());
ss << boost::apply_visitor (stringify (), tree);
return (out << ss.str ());
}
错误讯息:
In file included from /usr/local/include/boost/variant/apply_visitor.hpp:16:0,
from /usr/local/include/boost/variant/detail/hash_variant.hpp:23,
from /usr/local/include/boost/variant/variant.hpp:34,
from /usr/local/include/boost/variant.hpp:17,
from test2.cpp:5:
/usr/local/include/boost/variant/detail/apply_visitor_unary.hpp: In instantiation of ‘typename Visitor::result_type boost::apply_visitor(const Visitor&, Visitable&) [with Visitor = operator<<(std::ostream&, const int_tree_t&)::stringify; Visitable = const boost::make_recursive_variant<int, std::vector<boost::recursive_variant_, std::allocator<boost::recursive_variant_> > >; typename Visitor::result_type = std::__cxx11::basic_string<char>]’:
test2.cpp:50:43: required from here
/usr/local/include/boost/variant/detail/apply_visitor_unary.hpp:84:43: error: ‘const struct boost::make_recursive_variant<int, std::vector<boost::recursive_variant_, std::allocator<boost::recursive_variant_> > >’ has no member named ‘apply_visitor’
return visitable.apply_visitor(visitor);
^
如果我理解正确,boost::make_recursive_variant
应该创建一个与boost::variant
相同的类型...但是错误消息似乎表明它没有apply_visitor
功能,这是访问所必需的。我已经阅读了[this(http://www.boost.org/doc/libs/1_60_0/doc/html/variant/tutorial.html)页面,但没有任何关于必须使用带有递归变体的“特殊”访问模式。
我该如何编写这个程序?