I am using boost::program_options to parse command line parameters. I would like my program to echo the entered parameters back to the user for verification. This sounds like a simple task but I was unable to find an elegant solution.
The problem is that the user can enter all sorts of data types (strings, integer, boolean values, etc...). Usually this is handled nicely by boost. But I have troubles casting the values back to strings in order to echo them back to the user.
Here is what I am currently doing
// set up program options
po::options_description optdesc("Allowed options");
optdesc.add_options()
("help", "Produces this help screen")
("opt1", po::value<string>(), "Option 1")
("opt2", po::value<int>(), "Option 2")
("opt3", po::value<bool>(), "Option 3);
// parse command line
try
{
po::store(po::parse_command_line(argc, argv, optdesc), cmdline);
po::notify(cmdline);
}
// do error handling ...
// echo parameters back to user
for (po::variables_map::iterator it = cmdline.begin(); it != cmdline.end(); ++it)
{
boost::any arg = it->second.value();
if (typeid(string) == arg.type())
{
cout << " " << it->first << ": " << boost::any_cast<string>(it->second.value()) << endl;
}
else if (typeid(int) == arg.type())
{
cout << " " << it->first << ": " << boost::any_cast<int>(it->second.value()) << endl;
}
// etc...
I really don't like this solution. Since Boost is able to convert the user input from a string to the appropiate value it should also be able to convert the value back to a string representation without me explicitly testing for the data type.
Is this possible? If yes, how can I do that.
Thanks