如何将 Boost Variant 与结构对象 C++ 一起使用

How to use Boost Variant with struct objects C++

我有两个 类,根据 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";

感谢任何帮助。

变体类型没有 .hello.bye 成员。您可以通过 "visitor" 函数访问它们。但是您仍然必须决定当访问者未应用于正确的类型时要做什么。我认为您没有按照预期的方式使用 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;
};