How to print boost::any to a stream?

前端 未结 9 1290
悲哀的现实
悲哀的现实 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 07:58

    Define some aux function to output to stream:

    template
    bool out_to_stream(std::ostream& os, const boost::any& any_value)
    {
        try {
            T v = boost::any_cast(any_value);
            os << v;
            return true;
        } catch(boost:: bad_any_cast& e) {
            return false;
        }
    }
    

    You can define a special formatting for some types

    template<>
    bool out_to_stream(std::ostream& os, const boost::any& any_value)
    {
        try {
            std::string v(std::move(boost::any_cast(any_value)));
            os << "'" << v << "'";
            return true;
        } catch(boost:: bad_any_cast& e) {
            return false;
        }
    }
    

    or

    template<>
    bool out_to_stream(std::ostream& os, const boost::any& any_value)
    {
        try {
            os << ((boost::any_cast(any_value))? "yes" : "no");
            return true;
        } catch(boost:: bad_any_cast& e) {
            return false;
        }
    }
    

    Then define an output operator for boost::any where you list all types you want to try to cast and output

    std::ostream& operator<<(std::ostream& os, const boost::any& any_value)
    {
        //list all types you want to try
        if(!out_to_stream(os, any_value))
        if(!out_to_stream(os, any_value))
        if(!out_to_stream(os, any_value))
        if(!out_to_stream(os, any_value))
            os<<"{unknown}"; // all cast are failed, an unknown type of any
        return os;
    }
    

    And then for a value_type:

    std::ostream& operator<<(std::ostream& os, const boost::program_options::variable_value& cmdline_val)
    {
        if(cmdline_val.empty()){
            os << "";
        } else {
            os<

提交回复
热议问题