2014-10-09 103 views
0

我最近開始使用Boost C++庫,並且正在測試可以容納任何數據類型的any類。實際上,我試圖定義operator<<以輕鬆打印any類型的任何變量的內容(當然,內容的類別也應該有operator<<)。 我只開始樣本類型(int,double ...),因爲它們默認顯示。直到現在,我有這個代碼:Cast boost ::將任何實例轉換爲其實際類型

#include <boost/any.hpp> 
#include <iostream> 
#include <string> 
using namespace std; 
using namespace boost; 

ostream& operator<<(ostream& out, any& a){ 
    if(a.type() == typeid(int)) 
     out << any_cast<int>(a); 
    else if(a.type() == typeid(double)) 
     out << any_cast<double>(a); 
    // else ... 
    // But what about other types/classes ?! 
} 

int main(){ 
    any a = 5; 
    cout << a << endl; 
} 

所以這裏的問題是,我必須枚舉所有可能的類型。有沒有辦法將變量轉換爲particular typetype_info這個particular type

+1

無法枚舉「所有可能的類型」。該類型被稱爲* any *,而不是* every *。 – 2014-10-09 00:07:06

+0

也許您可以使用[Boost type erasure](http://www.boost.org/doc/libs/1_55_0/doc/html/boost_typeerasure.html)獲取更具體的類型擦除需求。就目前而言,這個問題令人困惑,因爲標題是關於演員的(這可能是錯誤的或不明智的),而機構是關於格式化的,這是一個很好理解而且不同的問題。 – 2014-10-09 00:08:04

+0

我從來沒有使用'boost :: any',而且我寫了一些非常奇怪的代碼。你也不需要使用它。它的用途很少。 – 2014-10-09 00:12:40

回答

1

Boost.Any any

隨着boost::any,你不能這樣做,因爲其他人在評論中已經指出。這是因爲boost::any忘記了它存儲的值的類型的一切,並要求您知道那裏是什麼類型。雖然你無法枚舉每種可能的類型。

解決方案是更改boost::any,以便忘記它存儲的值的類型,除了如何將其流出。 Mooing Duck在評論中提供了一個解決方案。另一種方法是編寫boost::any的新版本,但擴展其內部以支持流操作。

Boost.Spirit hold_any

Boost.Spirit已經提供了類似的東西在<boost/spirit/home/support/detail/hold_any.hpp>

Boost.TypeErasure any

一個更好的辦法,然而,使用Boost.TypeErasureany如被Kerrek SB在他的評論中提到。

爲你的情況(使用<<)的一個例子是這樣的:

#include <boost/type_erasure/any.hpp> 
#include <boost/type_erasure/operators.hpp> 
#include <iostream> 
#include <string> 

int main() { 
    typedef 
     boost::type_erasure::any< 
      boost::mpl::vector< 
       boost::type_erasure::destructible<>, 
       boost::type_erasure::ostreamable<>, 
       boost::type_erasure::relaxed 
      > 
     > my_any_type; 

    my_any_type my_any; 

    my_any = 5; 
    std::cout << my_any << std::endl; 
    my_any = 5.4; 
    std::cout << my_any << std::endl; 
    my_any = std::string("text"); 
    std::cout << my_any << std::endl; 
} 
相關問題