Question

I'm using boost::program_options, and this question is merely aesthetic.

How can I force a std::string option (or better, all options) to use only long form with "="?

Right now, all I see is "=" being forced on my int option, while the string isn't using the equal sign:

    po::options_description desc("Allowed options");
    desc.add_options()
        (opt_help, "Show this help message")
        (opt_int,  po::value<int>()->implicit_value(10), "Set an int")
        (opt_str,  po::value<std::string>()->implicit_value(std::string()), "Set a string")
    ;

The above shows all options as --help, --int=4, --str FooBar. I'd like options only in the form --option=something.

I've tried some styles, but I didn't find the right one.

Cheers!

Était-ce utile?

La solution

There is no way to do such thing, without writing your own parser.

http://www.boost.org/doc/libs/1_54_0/doc/html/program_options/howto.html#idp123407504

std::pair<std::string, std::string> parse_option(std::string value)
{
   if (value.size() < 3)
   {
      throw std::logic_error("Only full keys (--key) are allowed");
   }
   value = value.substr(2);
   std::string::size_type equal_sign = value.find('=');
   if (equal_sign == std::string::npos)
   {
      if (value == "help")
      {
         return std::make_pair(value, std::string());
      }
      throw std::logic_error("Only key=value settings are allowed");
   }
   return std::make_pair(value.substr(0, equal_sign),
   value.substr(equal_sign + 1));
}

// when call parse

po::store(po::command_line_parser(argc, argv).options(desc).
extra_parser(parse_option).run(), vm);

However, you can do this in more simple way

void check_allowed(const po::parsed_options& opts)
{
   const std::vector<po::option> options = opts.options;
   for (std::vector<po::option>::const_iterator pos = options.begin();
        pos != options.end(); ++pos)
   {
      if (pos->string_key != "help" &&
      pos->original_tokens.front().find("=") == std::string::npos)
      {
         throw std::logic_error("Allowed only help and key=value options");
      }
   }
}

po::parsed_options opts = po::command_line_parser(argc, argv).options(desc).
style(po::command_line_style::allow_long | 
po::command_line_style::long_allow_adjacent).run();
check_allowed(opts);

So, in this case boost::po parse and you simply check.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top