我最近开始使用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
的{{1}}?
答案 0 :(得分: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
然而,更好的方法是使用Kerrek SB在评论中提到的Boost.TypeErasure any
。
您的案例(使用<<
)的示例如下所示:
#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;
}