我正在尝试使用自定义类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 );
}
最佳答案
首先, 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
}
关于c++ - 带有自定义类的 boost 变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15186527/