错误处理

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!