促进。手持variables_map。服用具有优点指定在options_desctription类型 [英] Boost. Handy variables_map. Taking advantage of having specified the type in the options_desctription

查看:399
本文介绍了促进。手持variables_map。服用具有优点指定在options_desctription类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C ++ 升压/ program_options ,当我建 options_description 我指定每个选项的类型( FS ::路径在这种情况下):

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");

和我建立 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>()

而不是

vm["input"]

是否有访问变量映射的一些方便的方法?
不能升压利用从我已指定类型的事实 VARIABLE_VALUE 保存在 VM

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.

推荐答案

这是在那里你会使用通知功能从的 存储的库的组成部分。

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

<大骨节病> 住在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"

这篇关于促进。手持variables_map。服用具有优点指定在options_desctription类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆