How to print boost::any to a stream?

前端 未结 9 1287
悲哀的现实
悲哀的现实 2020-12-03 07:48

I have a Map std::map, which comes from the boost::program_options package. Now I would like to print the content o

相关标签:
9条回答
  • 2020-12-03 08:07

    I think you have to cover each possible case of objects you have to print... Or use boost::variant.

    EDIT: Sorry, I thought I shall write WHY.

    The reason why I think that is because, looking at any source code, it seems to rely on the fact that YOU provide the types when inserting and getting data. When you insert, data is automatically detected by the compiler, so you don't have to specify it. But when you get the data, you shall use any_cast, because you're not sure of the data type you're getting.

    If it worked in a different way and data type was sure, I think that would be no need for any_cast :)

    Instead, variant have a limited set of possible data types, and this information is somewhat registered, giving you the ability to iterate in a generic way a variant container.

    If you need this kind of manipulation - iterating a generic set of values - I think you shall use variant.

    0 讨论(0)
  • 2020-12-03 08:11

    Try using xany https://sourceforge.net/projects/extendableany/?source=directory xany class allows to add new methods to any's existing functionality. By the way there is a example in documentation which does exactly what you want.

    0 讨论(0)
  • 2020-12-03 08:15

    Unfortunately, with any the only way is to use the type() method to determine what is contained within any, then cast it with any_cast. Obviously you must have RTTI enabled, but you probably already do if you're using any:

    for(po::variables_map::const_iterator it = vm.begin(); it != vm.end(); ++it) {
      if(typeid(float) == it->second.type()) {
          std::cerr << it->first << ": " << any_cast<float>(it->second) << std::endl;
      }
      else if(typeid(int) == it->second.type()) {
          std::cerr << it->first << ": " << any_cast<int>(it->second) << std::endl;
      }
      ...
    }
    
    0 讨论(0)
提交回复
热议问题