我正在尝试使用定制类的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 );
}发布于 2013-03-03 22:22:28
首先,boost::static_visitor<>的模板参数应该指定调用操作符返回的类型。在本例中,ca_visitor的调用操作符返回一个CA const&,而不是一个CA。
但这并不是最大的问题。最大的问题是,您似乎对variant<>和static_visitor<>应该如何工作有误解。
boost::variant<>的思想是,它可以保存您在模板参数列表中指定的任何类型的值。您不知道该类型是什么,因此您为访问者提供了几个重载的调用操作符来处理每种可能的情况。
因此,当您提供一个访问器时,您需要确保它具有接受您的variant可以容纳的类型的所有必要的operator()重载。如果您没有做到这一点,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
}https://stackoverflow.com/questions/15186527
复制相似问题