2013-03-27 4 views
0

자바에서는 유형을 지정하지 않고 일반 클래스의 변수를 정의 할 수 있습니다.부스트 :: 변종; 방문자 클래스 정의

class Tree<T extends Comparable<? super T>> {} 
somewhere-else: Tree tree; 

다음 파일에서 일부 개체를 읽고 그것을 원하는 클래스 형식으로 형식 변환 할 수 있습니다.

tree = (Tree<String>) some object; 

boost::variant 나는 변형 정의를 시작했습니다.

typedef boost::variant<Tree<std::string>, Tree<int>> TreeVariant; TreeVariant tree; 

나는 내가 visitor class를 지정해야하지만, 같은 내 tree 변수 중 하나 Tree<std::string> 또는 Tree<int>에 할당 할 수 있음을 정의하는 방법을 this example에서 명확하지 않다 알고있다.

여기서부터 변수 tree을 사용하여 Tree의 멤버 함수를 호출하고 싶습니다.

답변

5

boost::variant에 값을 할당 할 방문자를 만들 필요가 없습니다. 튜토리얼의 Basic Usage 부분에 나타낸 바와 같이, 당신은 단지 값 지정 : 또한 static_visitor에서 값을 반환 할 수 있습니다

class TreeVisitor : public boost::static_visitor<> 
{ 
public: 
    void operator()(Tree<std::string>& tree) const 
    { 
    // Do something with the string tree 
    } 

    void operator()(Tree<int>& tree) const 
    { 
    // Do something with the int tree 
    } 
}; 

boost::apply_visitor(TreeVisitor(), tree); 

: 멤버 함수를 호출에 관해서는

TreeVariant tree; 
Tree<std::string> stringTree; 
Tree<int> intTree; 
tree = stringTree; 
tree = intTree; 

을, 당신은 방문자를 사용해야합니다 like :

class TreeVisitor : public boost::static_visitor<bool> 
{ 
public: 
    bool operator()(Tree<std::string>& tree) const 
    { 
    // Do something with the string tree 
    return true; 
    } 

    bool operator()(Tree<int>& tree) const 
    { 
    // Do something with the int tree 
    return false; 
    } 
}; 

bool result = boost::apply_visitor(TreeVisitor(), tree); 
+0

어디에서 boost :: apply_visitor를 호출할까요? 그것은 방문자의 구성원 기능이 있어야합니까? 나는 이것에 대해 확신하지 못한다. – Mushy

+0

'boost :: apply_visitor'는'boost' 네임 스페이스의 자유 함수입니다. 코드 예제의 마지막 줄에는이를 호출하는 방법이 나와 있습니다. – reima

+2

코드에 따라 TreeVisitor에 템플릿 멤버 함수 operator()를 만들 수도 있습니다.이 연산자는 모든 유형의 Tree를 허용합니다. 이것은 조작이 트리 내의 데이터 유형을 인식 할 필요가없는 경우에 유용 할 수 있습니다. –