Boost. Handy variables_map. Taking advantage of ha

2019-08-11 02:30发布

问题:

Using boost/program_options in c++, when I build the options_description I specify each option's type (fs::path in this case):

namespace fs = boost::filesystem;
namespace po = boost::program_options;

po::options_description desc("Example");
desc.add_options()
  ("help", "Print help messages")
  ("input,i", po::value<fs::path>(), "Input folder");

and I build the variables_map

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

When I access the option I have to specify again their type:

vm["input"].as<fs::path>()

and not

vm["input"]

Is there some more handy way of accessing the variables map? Can't boost take advantage from the fact that I already specified the type of the variable_value stored in vm?

I saw that many programmers end up in storing the option in another variable

fs::path input = vm["input"].as<fs::path>()

but I would like to avoid defining redundant variables.

回答1:

This is where you would use the notify feature from the Storage component of the library.

Live On Coliru

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

namespace po = boost::program_options;

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

    po::options_description desc("Example");

    int i = -99; // some value
    fs::path v;  // the only place where we ever specify the type!

    desc.add_options()
      ("help", "Print help messages")
      ("value,v", po::value(&i)->default_value(42),          "Input folder")
      ("input,i", po::value(&v)->default_value("TheAnswer"), "Input folder");

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

    std::cout << i << ", " << v << "\n";
}

Here the conversions as well as type-specifications themselves are implicit. Output:

./test
42, "TheAnswer"

./test -i /temp/path/foo --value=123
123, "/temp/path/foo"