如何将 boost::any 打印到流?

2024-03-30

我有一张地图std::map<std::string, boost::any>,它来自boost::program_options包裹。现在我想打印该地图的内容:

for(po::variables_map::const_iterator it = vm.begin(); it != vm.end(); ++it) {
  std::cerr << it->first << ": " << it->second << std::endl;
}

不幸的是,这是不可能的,因为boost::any没有operator<<定义的。

打印该地图最简单的方法是什么?

我可以为任何自动尝试强制转换的对象定义自己的输出运算符any到 int,然后是 double,然后是 string 等等,每次都忽略错误并尝试进行转换,直到转换成功并且我可以打印为指定的类型。

但Boost中应该有更简单的方法吧?我需要类似反向的东西lexical_cast...


你可以使用boost::spirit::hold_any反而。它在这里定义:

#include <boost/spirit/home/support/detail/hold_any.hpp>

并且完全兼容boost::any。与以下类别相比,该类别有两个不同之处:boost::any:

  • 它利用小对象优化习惯和一些其他优化技巧,使得spirit::hold_any比以下更小且更快boost::any
  • 它有流媒体运算符(operator<<() and operator>>())定义,允许输入和输出spirit::hold_any无缝地。

唯一的限制是你不能输入空的spirit::hold_any,但它需要保存输入所期望的类型的实例(可能是默认构造的)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 boost::any 打印到流? 的相关文章

随机推荐