我最近開始使用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 type
,type_info
這個particular type
?
無法枚舉「所有可能的類型」。該類型被稱爲* any *,而不是* every *。 – 2014-10-09 00:07:06
也許您可以使用[Boost type erasure](http://www.boost.org/doc/libs/1_55_0/doc/html/boost_typeerasure.html)獲取更具體的類型擦除需求。就目前而言,這個問題令人困惑,因爲標題是關於演員的(這可能是錯誤的或不明智的),而機構是關於格式化的,這是一個很好理解而且不同的問題。 – 2014-10-09 00:08:04
我從來沒有使用'boost :: any',而且我寫了一些非常奇怪的代碼。你也不需要使用它。它的用途很少。 – 2014-10-09 00:12:40