使用 Boost 库程序选项的必需参数和可选参数 [英] Required and Optional Arguments Using Boost Library Program Options

查看:40
本文介绍了使用 Boost 库程序选项的必需参数和可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Boost 程序选项库来解析命令行参数.

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

我有以下要求:

  1. 一旦提供了帮助",所有其他选项都是可选的;
  2. 如果未提供帮助",则需要所有其他选项.

我该如何处理?这是我处理这个的代码,我发现它很多余,我认为一定有一个容易做到的,对吧?

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
}

推荐答案

我自己也遇到过这个问题.解决方案的关键是函数 po::store 填充 variables_mappo::notify 会引发遇到的任何错误,所以 vm 可以在发送任何通知之前使用.

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.

因此,根据 蒂姆,根据需要将每个选项设置为必需,但在处理了帮助选项后运行 po::notify(vm).这样它就会退出而不会抛出任何异常.现在,将选项设置为必需,缺少选项将导致 required_option 异常被抛出并使用它的 get_option_name 方法你可以将你的错误代码减少到一个相对简单的 catch堵塞.

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.

作为附加说明,您的选项变量是直接通过 po::value< 设置的.-type- >( &var_name ) 机制,因此您不必通过 vm["opt_name"].as< 访问它们.-type- >().

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- >().

Peters 的回答

这篇关于使用 Boost 库程序选项的必需参数和可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆