本文介绍了如何将 boost::any 打印到流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

I have a Map std::map<std::string, boost::any>, which comes from the boost::program_options package. Now I would like to print the content of that map:

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

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

Unfortunately, that is not possible because boost::any doesn't have an operator<< defined.

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

What is the easiest way to print that map?

我可以为任何自动尝试将每个 any 转换为 int、double、string 等的输出操作符定义我自己的输出操作符,每次忽略错误并尝试转换直到转换成功,我可以按指定类型打印.

I could define my own output operator for any that automatically tries to cast each any to an int, then double, then string, etc., each time ignoring errors and trying to cast until the cast is successful and I can print as the specified type.

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

But there should be an easier method in Boost? I'd need something like a reverse lexical_cast...

推荐答案

您可以使用 boost::spirit::hold_any 代替.它在这里定义:

You could use boost::spirit::hold_any instead. It's defined here:

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

并且与 boost::any 完全兼容.与 boost::any 相比,这个类有两个不同:

and is fully compatible with boost::any. This class has two differences if compared to boost::any:

  • 它利用了小对象优化习惯用法和其他一些优化技巧,使 spirit::hold_anyboost::any 更小、更快
  • 它定义了流操作符(operator< 和 operator>>()),允许输入和输出 精神::hold_any 无缝.
  • it utilizes the small object optimization idiom and a couple of other optimization tricks, making spirit::hold_any smaller and faster than boost::any
  • it has the streaming operators (operator<<() and operator>>()) defined, allowing to input and output a spirit::hold_any seemlessly.

唯一的限制是你不能输入一个空的spirit::hold_any,但它需要持有一个(可能是默认构造的)输入类型的实例.

The only limitation is that you can't input into an empty spirit::hold_any, but it needs to be holding a (possibly default constructed) instance of the type which is expected from the input.

这篇关于如何将 boost::any 打印到流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:00