我有两个类,根据key
的性质,我想从boost::variant
中获取结构值。代码如下所示。
#include <iostream>
#include <boost/variant.hpp>
using namespace std;
class A {
public:
struct greeting {
string hello;
};
class B {
public:
struct greeting {
string bye;
};
};
typedef boost::variant<A::greeting, B::greeting> greet;
greet getG(string key) {
greet g;
if (key == "A") {
g.hello = "MY ENEMY"; // this line doesn't work
}
else {
g.bye = "MY FRIEND"; // nor this line
}
return g;
};
int main() {
A a;
B b;
greet h = getG("A");
A::greeting my = boost::get<A::greeting>(h);
cout << my.hello << endl;
return 0;
}
我得到的确切错误是:
error: no member named 'hello' in 'boost::variant<A::greeting, B::greeting, boost::detail::variant::void_, boost::detail::variant::void_, ...>' g.hello = "MY ENEMY";
和
error: no member named 'bye' in 'boost::variant<A::greeting, B::greeting, .../>' g.bye = "MY FRIEND";
感谢任何帮助。
答案 0 :(得分:2)
变体类型没有.hello
和.bye
成员。您可以通过“访客”功能访问它们。但是,当访问者未应用于正确的类型时,您仍需要决定该怎么做。我认为你没有以预期的方式使用Boost.Variant。 (例如条件调味不好)。
http://www.boost.org/doc/libs/1_61_0/doc/html/variant/reference.html#variant.concepts.static-visitor
struct hello_visitor : boost::static_visitor<>{
string const& msg;
hello_visitor(string const& msg) : msg(msg){}
void operator()(A::greeting& t) const{
t.hello = msg;
}
void operator()(B::greeting& t) const{
// throw? ignore? other?
}
};
struct bye_visitor : boost::static_visitor<>{
string const& msg;
bye_visitor(string const& msg) : msg(msg){}
void operator()(A::greeting& t) const{
// throw? ignore? other?
}
void operator()(B::greeting& t) const{
t.bye = msg;
}
};
greet getG(string key) {
greet g;
if (key == "A") { // is "key" handling the type, if so you can delegate this to the library instead of doing this.
boost::apply_visitor(hello_visitor("MY ENEMY"), g);
}
else {
boost::apply_visitor(bye_visitor("MY FRIEND"), g);
}
return g;
};