2017-04-10 9 views
1

두 클래스가 있으며 key의 성격에 따라 boost::variant에서 구조체 값을 가져오고 싶습니다. 코드는 다음과 같습니다. 내가 얻고Boost Variant를 struct 객체와 함께 사용하는 방법 C++

#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

라인 번호를 쉽게 특정 라인을 찾을 수 있습니다하지만, 그것은 또한 매우 열심히한다. 오류가있는 행을 표시하는 주석이면 충분합니다. –

+0

문제에 대해서는 특정 구조에 대한 참조를 얻으려면 ['boost :: get'] (http://www.boost.org/doc/libs/1_63_0/doc/html/boost/get_idp1003723808.html)를 사용하십시오 . (사용 방법에 대한 예제는 [Boost variant tutorial] (http://www.boost.org/doc/libs/1_63_0/doc/html/variant/tutorial.html)을 참조하십시오. –

답변

2

변형 유형에는 .hello.bye 명의 회원이 없습니다. "방문자"기능을 통해 액세스 할 수 있습니다. 그러나 방문자가 올바른 유형에 적용되지 않을 때 수행 할 작업을 결정해야합니다. 나는 당신이 부스트를 사용하지 않는 것 같아요. 사용하려는 의도대로 변합니다. 예를 들어, 조건문은 잘 냄새를 맡지 않습니다. 우리가 코드를 복사하고 그것을 자신을 시도하는

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; 
}; 
+0

방금 ​​선을 제거했습니다. 번호. 코드를 테스트 한 결과,'error : bye_visitor와 hello_visitor 호출에 맞는 함수가 없습니다. 내가 누락 된 부분을 지적 해 주겠니? – pseudo

+0

이 코드는 이제 작동합니다. 당신이하고 싶은 것을 완전히 분명하지는 않습니다. 당신은 실제 Boost.Variant와 (당신의 조건과 함께) 몇 가지 수동 변형을 혼합하는 것 같습니다. Boost.Variant의 아이디어는 "실제 유형"의 의사 결정 트리를 다룰 필요가 없다는 것입니다. – alfC

+0

내가 필요한 것. 고맙습니다. – pseudo