錯誤處理

boost::program_options::notify 可用於報告引數傳遞中的任何錯誤

#include <boost/program_options.hpp>
#include <string>
#include <iostream>

int main(int argc, char** argv) {
  namespace po = boost::program_options;

  po::variables_map vm;
  po::options_description desc("Allowed Options");

  // declare options
  desc.add_options()
    ("name", po::value<std::string>()->required(), "Type your name to be greeted!");

  // parse arguments
  po::store(po::parse_command_line(argc, argv, desc), vm);

  // check arguments
  try {
    po::notify(vm);
  } catch (std::exception& e) {
    std::cout << "Error: " << e.what() << std::endl;
    std::cout << desc << std::endl;
    return 1;
  }

  // program logic
  std::cout << "Hello " << vm["name"].as<std::string>() << std::endl;

  return 0;
}

傳遞非法引數會產生有用的錯誤訊息

 $ ./a.out
Error: the option '--name' is required but missing
Allowed Options:
  --name arg            Type your name to be greeted!