我最近开始使用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