我最近开始使用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;
}
所以这里的问题是我必须枚举所有可能的类型。有没有办法将变量转换为particular type
具有type_info
this 的particular type
?