【发布时间】:2014-10-09 00:05:49
【问题描述】:
我最近开始使用Boost C++ 库,我正在测试可以保存任何数据类型的any 类。实际上,我正在尝试定义operator<< 以轻松打印any 类型的任何变量的内容(当然,内容的类也应该定义operator<<)。
我只从样本类型开始(int、double ...),因为它们默认显示。到现在为止,我有这个代码:
#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;
}
所以这里的问题是我必须枚举所有可能的类型。有没有办法将变量转换为具有 type_info 的 particular type 的 particular type ?
【问题讨论】:
-
你不能枚举“所有可能的类型”。该类型称为 any,而不是 every。
-
也许您可以使用Boost type erasure 来满足更具体的类型擦除需求。就目前而言,这个问题令人困惑,因为标题是关于铸造的(这可能是错误的或不明智的),而正文是关于格式的,这是一个易于理解且完全不同的问题。
-
我从未使用过
boost::any,而且我写了一些非常奇怪的代码。你也不需要使用它。它的用途难以置信地很少。 -
@webNeat:这听起来像是一个经典的 X-Y 问题。
-
@BryanChen:您可以在删除
operator<<的同时boost::any删除数据:coliru.stacked-crooked.com/a/de70c25df7302c7f,但这很 hack。
标签: c++ boost casting boost-any