【问题标题】:How to reassemble command line string using Boost Program Options?如何使用 Boost Program Options 重新组装命令行字符串?
【发布时间】:2021-07-10 22:42:57
【问题描述】:
  • 我使用 Boost Program Options as usual 解析了命令行。 po::command_line_parser 填充po::variables_map vm

  • 我更改了po::variables_map 中的一些值,如下所示:

    vm.at(option).value() = val;

  • 现在我需要从po::variables_map 重新组装修改后的命令行字符串。如何做到这一点?

【问题讨论】:

    标签: c++ boost-program-options


    【解决方案1】:

    程序选项po:variables_map vm 具有类型: std::map<std::string, variable_value>

    variable_value 将值存储在 boost::any v; boost::any 的使用会影响解决方案:

    string ProgramOptions::getCommandLine()
    {
        using boost::any_cast;
        ostringstream cmdLine;
        for (auto i : _vm)
        {
            string dashForm = i.first.length() == 1 ? "-" : "--";
            cmdLine << dashForm << i.first << " ";
            boost::any value(i.second.value());
            if (auto *const v = any_cast<int>(&value))
                cmdLine << *v;
            else if(auto* const v = any_cast<string>(&value))
                cmdLine << *v;
            cmdLine << " ";
        }
        return cmdLine.str();
    }
    

    【讨论】:

    • 你可以使用if(auto *const asInt = any_cast&lt;int&gt;(&amp;i.second))而不是手动检查类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多