15

如果没有多头期权的提振,人们将如何指定空头期权?

(",w", po::value<int>(), "Perfrom write with N frames")

生成这个

-w [ -- ] arg : Perfrom write with N frames

有什么方法可以只指定短选项吗?

4

1 回答 1

15

如果您使用的是命令行解析器,有一种方法可以设置不同的样式。因此解决方案是仅使用长选项并启用允许长选项以一个破折号指定的allow_long_disguise 样式(即“-long_option”)。这是一个例子:

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

namespace options = boost::program_options;
using namespace std;

int
main (int argc, char *argv[])
{
        options::options_description desc (string (argv[0]).append(" options"));
        desc.add_options()
            ("h", "Display this message")
        ;
        options::variables_map args;
        options::store (options::command_line_parser (argc, argv).options (desc)
                        .style (options::command_line_style::default_style |
                                options::command_line_style::allow_long_disguise)
                        .run (), args);
        options::notify (args);
        if (args.count ("h"))
        {
            cout << desc << endl;
            return 0;
        }
}

但是描述输出会有一点问题:

$ ./test --h
./test options:
  --h                   Display this message

而且那个很难修复,因为这是用于形成此输出的内容:

std::string
option_description::format_name() const
{
    if (!m_short_name.empty())
        return string(m_short_name).append(" [ --").
        append(m_long_name).append(" ]");
    else
        return string("--").append(m_long_name);
}

想到的唯一解决方法是将结果字符串中的“--”替换为“-”。例如:

#include <iostream>
#include <sstream>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/replace.hpp>

namespace options = boost::program_options;
using namespace std;

int
main (int argc, char *argv[])
{
        options::options_description desc (string (argv[0]).append(" options"));
        desc.add_options()
            ("h", "Display this message")
        ;
        options::variables_map args;
        options::store (options::command_line_parser (argc, argv).options (desc)
                        .style (options::command_line_style::default_style |
                                options::command_line_style::allow_long_disguise)
                        .run (), args);
        options::notify (args);
        if (args.count ("h"))
        {
            std::stringstream stream;
            stream << desc;
            string helpMsg = stream.str ();
            boost::algorithm::replace_all (helpMsg, "--", "-");
            cout << helpMsg << endl;
            return 0;
        }
}

您可以做的最好的事情是修复打印空长选项描述的代码并将补丁发送给库的作者。

于 2010-09-01T20:32:49.740 回答