C++ Boost Program Options

Da Andreabont's Wiki.

Le boost forniscono un meccanismo per prelevare i prametri forniti da linea di comando al lancio dell'eseguibile.

Codice

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

int main(int argc, char **argv) {

  boost::program_options::options_description po("Opzioni disponibili:");
  po.add_options()
        ("help", "stampa lista opzioni")
        ("int_val", boost::program_options::value<int>(), "inserisci valore numerico")
        ("string_val", boost::program_options::value<std::string>(), "inserisci string")
        ("bool_val", boost::program_options::value<bool>(), "inserisci true/false")
  ;

  boost::program_options::variables_map vm;
  boost::program_options::store(boost::program_options::parse_command_line(argc, argv, po), vm);
  boost::program_options::notify(vm);

  if (vm.count("help")) {
      std::cout << po << std::endl;
      return 0;
  }
  
  if(vm.count("int_val")) {
      std::cout << "int_val: " << vm["int_val"].as<int>() << std::endl;
  }
  
  if(vm.count("string_val")) {
      std::cout << "string_val: " << vm["string_val"].as<std::string>() << std::endl;
  }
  
  if(vm.count("bool_val")) {
      std::cout << "bool_val: " << std::boolalpha << vm["bool_val"].as<bool>() << std::endl;
  }

}

Compilare

g++ -std=c++11 <file.cpp> -lboost_program_options