2015-12-12 70 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");的幫助程序功能

相關問題