2015-12-12 72 views
-1

比方说,我有这包括:有没有办法让这个更短更清晰?

#include <map> 
#include <boost/any.hpp> 
#include <string> 

,代码:

int main() 
{ 
    typedef std::map< std::string, boost::any > table; 
    table foobar; 
    foobar["foo"] = table(); 
    table* foobarfoo = boost::any_cast< table* >(foobar["foo"]); 
    (*foobarfoo)["bar"] = int(5); 
    int* test = boost::any_cast< int* >((*foobarfoo)["bar"]); 
} 

这工作得很好,虽然它并没有真正好看,尤其是当我需要从map(int* test here)带指针在一行中。 我真的很想在这里看到的是这样的事情:

int main() 
{ 
    typedef std::map< std::string, boost::any > table; 
    table foobar; 
    foobar["foo"] = table(); 
    foobar["foo"]["bar"] = int(5); 
    int* test = boost::any_cast< int* >(foobar["foo"]["bar"]); 
} 

这看起来很多,更清晰,但它不会这样的。我的问题是,是否有办法让第二个代码有点小修改,或者有一种方法看起来和第二个例子一样好,但仍然有效?

+0

“更短”和“更清晰”是互斥的。 :P – Casey

回答

0

您可以将any对象转换为引用类型。

在这种情况下,有上最后一行丑陋的双any_cast

int main() 
{ 
    typedef std::map< std::string, boost::any > table; 
    table foobar; 
    foobar["foo"] = table(); 
    table& foo_table = boost::any_cast< table& >(foobar["foo"]); 
    foo_table["bar"] = int(5); 
    int* test = boost::any_cast< int* >(&(foo_table["bar"])); 
} 

如果这样的:

int main() 
{ 
    typedef std::map< std::string, boost::any > table; 
    table foobar; 
    foobar["foo"] = table(); 
    boost::any_cast< table& >(foobar["foo"])["bar"] = int(5); 
    int* test = boost::any_cast< int* >(&(boost::any_cast< table& >(foobar["foo"])["bar"])); 
} 

可以通过保存一个参考第一投的resul使其更漂亮通常需要操作,您可以考虑更改外部地图的类型(如果没有,但将存储table s)或创建看起来像int* test = get_value<int>(foobar, "foo", "bar");的帮助程序功能

相关问题