代码之家  ›  专栏  ›  技术社区  ›  Novikov

仅在boost::program\u选项中有短选项

  •  15
  • Novikov  · 技术社区  · 14 年前

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

    生成此

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

    有没有办法只指定短选项?

    1 回复  |  直到 14 年前
        1
  •  15
  •   user405725 user405725    14 年前

    如果您使用的是命令行解析器,那么有一种方法可以设置不同的样式。因此,解决方案是只使用长选项,并启用allow\u long\u伪装样式,允许用一个破折号指定长选项(即“-long\u 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;
            }
    }
    

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