I have a Map std::map
, which comes from the boost::program_options
package. Now I would like to print the content o
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<