【问题标题】:Best way of handling level 2 commands with Boost ProgramOptions使用 Boost ProgramOptions 处理 2 级命令的最佳方式
【发布时间】:2015-03-16 16:31:27
【问题描述】:

我有兴趣在命令行上拥有一个执行 2 级命令的单个可执行文件 - 有点像 git commitgit add 是它们自己在一个 EXE 中的单独命令。所以我的问题是:有没有办法用 ProgramOptions 来简化它?我知道我可以定义不同的方案,然后针对特定字符串检查argv[1],但我希望有一种更简洁的方法。谢谢!

【问题讨论】:

    标签: c++ boost boost-program-options


    【解决方案1】:

    你可以使用positional parameters:

    #include <boost/program_options.hpp>
    
    #include <iostream>
    #include <algorithm>
    #include <iterator>
    
    namespace po = boost::program_options;
    
    // A helper function to simplify the main part.
    template<class T>
    std::ostream& operator<<(std::ostream& os, const std::vector<T>& v)
    {
      copy(v.begin(), v.end(), std::ostream_iterator<T>(os, " "));
      return os;
    }
    
    int main(int ac, char* av[])
    {
      try
        {
          po::options_description desc("Allowed options");
          desc.add_options()
            ("help", "produce help message")
            ("command", po::value<std::string>(), "command to execute")
            ("command_opt", po::value<std::vector<std::string> >(), "command options")
            ;
    
          po::positional_options_description p;
          p.add("command", 1);
          p.add("command_opt", -1);
    
          po::variables_map vm;
          po::store(po::command_line_parser(ac, av).
                    options(desc).positional(p).run(), vm);
          po::notify(vm);
    
          if (vm.count("help")) {
            std::cout << "Usage: options_description [options]\n";
            std::cout << desc;
            return 0;
          }
    
          if (vm.count("command"))
            {
              std::cout << "command: " << vm["command"].as<std::string>() << "\n";
            }
    
          if (vm.count("command_opt"))
            {
              std::cout << "command options: " << vm["command_opt"].as<std::vector<std::string> >() << "\n";
            }
    
        }
      catch(std::exception& e)
        {
          std::cout << e.what() << "\n";
          return 1;
        }
    }
    

    但是 AFAIK 您必须自己对哪个选项与哪个其他选项兼容的逻辑检查,因为在 boost 程序选项中没有依赖系统。

    here 所述,将每个命令选项分组到不同的选项组中可能有助于生成使用文本。

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 2016-01-15
      • 1970-01-01
      • 2014-12-20
      相关资源
      最近更新 更多