我正在尝试使用自定义类boost-variant
。我知道访问类内容的安全方法是使用boost::static_visitor
。你知道为什么下面的代码不能编译吗?对boost::static_visitor
的签名/声明是否有任何要求才能使用?
我发现了这个问题Why can't I visit this custom type with boost::variant?,但我没有得到它。
此致
AFG
#include <iostream>
#include <algorithm>
#include <boost/variant.hpp>
struct CA{};
struct ca_visitor : public boost::static_visitor<CA>
{
const CA& operator()(const CA& obj ) const { return obj;}
};
struct CB{};
struct cb_visitor : public boost::static_visitor<CB>
{
const CB& operator()(const CB& obj) const { return obj;}
};
int main(){
typedef boost::variant<
CA
,CB > v_type;
v_type v;
const CA& a = boost::apply_visitor( ca_visitor(), v );
}
答案 0 :(得分:4)
首先,boost::static_visitor<>
的模板参数应指定调用运算符返回的类型。在您的情况下,ca_visitor
的调用运算符返回CA const&
,而不是CA
。
但这不是最大的问题。最大的问题是您似乎对variant<>
和static_visitor<>
的工作方式存在误解。
boost::variant<>
的想法是它可以保存您在模板参数列表中指定的任何类型的值。您不知道该类型是什么,因此您为访问者提供了几个重载的调用操作符来处理每个可能的情况。
因此,当您提供访问者时,您需要确保其具有operator()
的所有必要重载,以便接受variant
可以容纳的类型。如果你没有这样做,Boost.Variant会导致生成编译错误(并且帮你一个忙,因为你忘了处理某些情况)。
这是您面临的问题:您的访问者没有呼叫操作员接受CB
类型的对象。
这是正确使用boost::variant<>
和static_visitor<>
的一个示例:
#include <iostream>
#include <algorithm>
#include <boost/variant.hpp>
struct A{};
struct B{};
struct my_visitor : public boost::static_visitor<bool>
// ^^^^
// This must be the same as the
// return type of your call
// operators
{
bool operator() (const A& obj ) const { return true; }
bool operator() (const B& obj) const { return false; }
};
int main()
{
A a;
B b;
my_visitor mv;
typedef boost::variant<A, B> v_type;
v_type v = a;
bool res = v.apply_visitor(mv);
std::cout << res; // Should print 1
v = b;
res = v.apply_visitor(mv);
std::cout << res; // Should print 0
}