87

Boost Program Options Library を使用して、コマンド ライン引数を解析しています。

次の要件があります。

  1. 「ヘルプ」が提供されると、他のすべてのオプションはオプションになります。
  2. 「ヘルプ」が提供されないと、他のすべてのオプションが必要になります。

どうすればこれに対処できますか?これを処理するコードは非常に冗長であることがわかりました。簡単に実行できるはずですよね?

#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 << "\n";
            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>() << "\n";
        }
        else
        {
            std::cout << "\"host\" is required!" << "\n";
            return false;
        }

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

        if (vm.count("config"))
        {
            std::cout << "config: " << vm["config"].as<std::string>() << "\n";
        }
        else
        {
            std::cout << "\"config\" is required!" << "\n";
            return false;
        }
    }
    catch(std::exception& e)
    {
        std::cerr << "Error: " << e.what() << "\n";
        return false;
    }
    catch(...)
    {
        std::cerr << "Unknown error!" << "\n";
        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
}
4

4 に答える 4

107

私は自分でこの問題に遭遇しました。解決策の鍵は、発生したエラーが発生したときに関数がデータをpo::store入力することです。これにより、通知が送信される前に使用できます。 variables_mappo::notifyvm

そのため、 Timに従って、必要に応じて各オプションを必須に設定しますがpo::notify(vm) 、ヘルプ オプションを処理した後に実行します。このようにして、例外がスローされることなく終了します。オプションを必須に設定すると、オプションが欠落しているとrequired_option例外がスローされ、そのget_option_nameメソッドを使用してエラーコードを比較的単純なcatchブロックに減らすことができます。

追加の注意として、オプション変数はpo::value< -type- >( &var_name )メカニズムを介して直接設定されるため、 を介してそれらにアクセスする必要はありませんvm["opt_name"].as< -type- >()

コード例Peters answerで提供されています

于 2011-04-01T19:09:14.083 に答える
49

以下は、rcollyer と Tim による完全なプログラムです。

#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)->required(),      "set the host server")
          ("port,p",   po::value<int>(&iport)->required(),             "set the server port")
          ("config,c", po::value<std::string>(&configDir)->required(), "set the config path")
        ;

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

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

        // There must be an easy way to handle the relationship between the
        // option "help" and "host"-"port"-"config"
        // Yes, the magic is putting the po::notify after "help" option check
        po::notify(vm);
    }
    catch(std::exception& e)
    {
        std::cerr << "Error: " << e.what() << "\n";
        return false;
    }
    catch(...)
    {
        std::cerr << "Unknown error!" << "\n";
        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;

  // else
  std::cout << "host:\t"   << host      << "\n";
  std::cout << "port:\t"   << port      << "\n";
  std::cout << "config:\t" << configDir << "\n";

  // Do the main routine here
}

/* Sample output:

C:\Debug>boost.exe --help
Program Usage:
  --help                produce help message
  -h [ --host ] arg     set the host server
  -p [ --port ] arg     set the server port
  -c [ --config ] arg   set the config path


C:\Debug>boost.exe
Error: missing required option config

C:\Debug>boost.exe --host localhost
Error: missing required option config

C:\Debug>boost.exe --config .
Error: missing required option host

C:\Debug>boost.exe --config . --help
Program Usage:
  --help                produce help message
  -h [ --host ] arg     set the host server
  -p [ --port ] arg     set the server port
  -c [ --config ] arg   set the config path


C:\Debug>boost.exe --host 127.0.0.1 --port 31528 --config .
host:   127.0.0.1
port:   31528
config: .

C:\Debug>boost.exe -h 127.0.0.1 -p 31528 -c .
host:   127.0.0.1
port:   31528
config: .
*/
于 2011-04-01T21:44:45.127 に答える
13

オプションが必須であることを簡単に指定できます [ 1 ]。たとえば、次のようにします。

..., value<string>()->required(), ...

しかし、私が知る限り、異なるオプション間の関係を program_options ライブラリに表す方法はありません。

1 つの可能性は、異なるオプション セットを使用してコマンド ラインを複数回解析することです。「ヘルプ」を既にチェックしている場合は、必要に応じて他の 3 つのオプションをすべて設定して再度解析できます。ただし、それがあなたが持っているものよりも優れていると考えるかどうかはわかりません.

于 2011-04-01T18:27:05.490 に答える