2013-03-27 64 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