Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

c++ - Required and Optional Arguments Using Boost Library Program Options

I'm using Boost Program Options Library to parse the command line arguments.

I have the following requirements:

  1. Once "help" is provided, all the other options are optional;
  2. Once "help" is not provided, all the other options are required.

How I can deal with this? Here is the my code handling this, and I found it's very redundant, and I think there must be an easy to do, right?

#include <boost/program_options.hpp>
#include <iostream>
#include <sstream>
namespace po = boost::program_options;

bool process_command_line(int argc, char** argv,
                          std::string& host,
                          std::string& port,
                          std::string& configDir)
{
    int iport;

    try
    {
        po::options_description desc("Program Usage", 1024, 512);
        desc.add_options()
          ("help",     "produce help message")
          ("host,h",   po::value<std::string>(&host),      "set the host server")
          ("port,p",   po::value<int>(&iport),             "set the server port")
          ("config,c", po::value<std::string>(&configDir), "set the config path")
        ;

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);

        if (vm.count("help"))
        {
            std::cout << desc << "
";
            return false;
        }

        // There must be an easy way to handle the relationship between the
        // option "help" and "host"-"port"-"config"
        if (vm.count("host"))
        {
            std::cout << "host:   " << vm["host"].as<std::string>() << "
";
        }
        else
        {
            std::cout << ""host" is required!" << "
";
            return false;
        }

        if (vm.count("port"))
        {
            std::cout << "port:   " << vm["port"].as<int>() << "
";
        }
        else
        {
            std::cout << ""port" is required!" << "
";
            return false;
        }

        if (vm.count("config"))
        {
            std::cout << "config: " << vm["config"].as<std::string>() << "
";
        }
        else
        {
            std::cout << ""config" is required!" << "
";
            return false;
        }
    }
    catch(std::exception& e)
    {
        std::cerr << "Error: " << e.what() << "
";
        return false;
    }
    catch(...)
    {
        std::cerr << "Unknown error!" << "
";
        return false;
    }

    std::stringstream ss;
    ss << iport;
    port = ss.str();

    return true;
}

int main(int argc, char** argv)
{
  std::string host;
  std::string port;
  std::string configDir;

  bool result = process_command_line(argc, argv, host, port, configDir);
  if (!result)
      return 1;

  // Do the main routine here
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've run into this issue myself. The key to a solution is that the function po::store populates the variables_map while po::notify raises any errors encountered, so vm can be used prior to any notifications being sent.

So, as per Tim, set each option to required, as desired, but run po::notify(vm) after you've dealt with the help option. This way it will exit without any exceptions thrown. Now, with the options set to required, a missing option will cause a required_option exception to be thrown and using its get_option_name method you can reduce your error code to a relatively simple catch block.

As an additional note, your option variables are set directly via the po::value< -type- >( &var_name ) mechanism, so you don't have to access them through vm["opt_name"].as< -type- >().

A code example is provided in Peters answer


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...