2013-03-27 62 views
0

在Java中,我能夠在不指定類型的情況下定義泛型類的變量。Boost :: Variant;定義訪問類

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

然後我可以從文件中,有些對象閱讀類型強制轉換爲類的類型我的願望。

tree = (Tree<String>) some object; 

With boost::variant我已經開始了一個變體定義。

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

我知道我需要指定一個visitor class但它不是從this example清楚如何定義它,使得我能夠分配給我的tree變量要麼Tree<std::string>Tree<int>

然後,我想從那裏繼續使用變量tree調用樹的成員函數。

回答

5

有沒有必要創建一個訪客爲boost::variant分配值。正如在本教程的Basic Usage部分所示,您只需指定值:

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

至於調用成員函數,你應該使用訪問者:

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); 

您也可以從static_visitor返回值,如下所示:

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 2013-03-27 14:48:25

+0

'boost :: apply_visitor'是'boost'命名空間中的一個自由函數。代碼示例中的最後一行顯示瞭如何調用它。 – reima 2013-03-27 15:49:23

+2

根據你的代碼,你也可以讓TreeVisitor有一個模板成員函數operator(),它接受任何類型的Tree。如果操作不需要知道樹中的數據類型,這可能很有用。 – 2013-03-27 16:33:36