【问题标题】:Echo entered command line parameters in BoostEcho在Boost中输入命令行参数
【发布时间】:2013-07-22 09:52:49
【问题描述】:

我正在使用boost::program_options 来解析命令行参数。我希望我的程序将输入的参数回显给用户进行验证。这听起来像是一项简单的任务,但我无法找到一个优雅的解决方案。

问题在于用户可以输入各种数据类型(字符串、整数、布尔值等...)。通常这可以通过 boost 很好地处理。但是我很难将这些值转换回字符串以便将它们回显给用户。

这是我目前正在做的事情

// set up program options
po::options_description optdesc("Allowed options");
optdesc.add_options()
    ("help", "Produces this help screen")
    ("opt1", po::value<string>(), "Option 1")
    ("opt2", po::value<int>(), "Option 2")
    ("opt3", po::value<bool>(), "Option 3);

// parse command line
try
{
    po::store(po::parse_command_line(argc, argv, optdesc), cmdline);
    po::notify(cmdline);
}

// do error handling ...

// echo parameters back to user
for (po::variables_map::iterator it = cmdline.begin(); it != cmdline.end(); ++it)
{
    boost::any arg = it->second.value();
    if (typeid(string) == arg.type())
    {
         cout << "  " << it->first << ":  " << boost::any_cast<string>(it->second.value()) << endl;
    }
    else if (typeid(int) == arg.type())
    {
         cout << "  " << it->first << ":  " << boost::any_cast<int>(it->second.value()) << endl;
    }
    // etc...

我真的不喜欢这个解决方案。由于 Boost 能够将用户输入从字符串转换为适当的值,因此它还应该能够将值转换回字符串表示形式,而无需我显式测试数据类型。

这可能吗?如果是,我该怎么做。

谢谢

【问题讨论】:

    标签: c++ boost casting boost-program-options


    【解决方案1】:

    您已经拥有argvargc,只需将它们回显给用户

    #include <iostream>
    #include <iterator>
    
    int
    main(int argc, char* argv[])
    {
        std::cout << "got " << argc << " args" << std::endl;
        std::copy(argv + 1, argv + argc, std::ostream_iterator<char*>(std::cout, " "));
        std::cout << std::endl;
    }
    

    生产

    samm:stackoverflow samm$ ./a.out asdf 1 2 3 hello world
    got 7 args
    asdf 1 2 3 hello world 
    samm:stackoverflow samm$
    

    无需遍历variables_map 并强制转换每个条目。

    【讨论】:

    • 感谢您的建议。当然,这是最简单的方法。然而,这只是我试图存档的一个最小示例。在某些情况下,这不是一个理想的解决方案:一个这样的例子是,如果解析值之一作为向量给出。当然,我可以自己简单地回显数据,但感觉不对。如果 Boost 完成了所有繁重的工作,他必须以某种方式利用这一点。
    【解决方案2】:

    我遇到了类似的问题,this 是我的解决方案。 简而言之,您必须为基于 boost::variant 的选项编写自己的容器,而不是 boots::any(boost::po 所基于的)。这个容器可以通过 boost::po 选项的通知器来填充。这将允许您将访问者模式用于您的选项并以通用方式处理它们。

    【讨论】:

      猜你喜欢
      • 2016-02-24
      • 2014-02-19
      • 2014-03-29
      • 2015-07-20
      • 1970-01-01
      • 2011-01-05
      • 2017-01-03
      相关资源
      最近更新 更多