【问题标题】:Use boost::program_options to specify multiple flags使用 boost::program_options 指定多个标志
【发布时间】:2020-05-02 19:02:20
【问题描述】:

我想使用 boost::program_options 来指定所需的详细程度,这很常见。例如。

./test -v # verbosity = 1 
./test -vvv # verbosity = 3 
./test -v blah blah -v # verbosity = 2 

我知道如何多次出现需要一个值的选项,但我想要的是多次出现一个开关。单个开关可以用类似的东西来完成

desc.add_options()
   ("verbosity,v", bool_switch(), "Increase verbosity");

但如果提供了多个 -v 选项,则会失败并出现 multiple_occurrences 异常。

多个布尔选项可以用类似的东西来完成

desc.add_options()
   ("verbose,v", value<std::vector<int> >(), "Increase verbosity");

但这需要给每个选项一个值,比如

./test -v 1 -v 1 -v 1

【问题讨论】:

    标签: c++ boost-program-options


    【解决方案1】:

    我遇到了这个确切的问题,并提出了以下问题。希望它对某人有用,即使对于原始海报来说为时已晚。

    #include "StdAfx.h"
    #include <boost\program_options.hpp>
    #include <iostream>
    
    namespace po = boost::program_options;
    
    class CountValue : public po::typed_value<std::size_t>
    {
    public:
        CountValue():
            CountValue(nullptr)
        {
        }
    
        CountValue(std::size_t* store):
            po::typed_value<std::size_t>(store)
        {
            // Ensure that no tokens may be passed as a value.
            default_value(0);
            zero_tokens();
        }
    
        virtual ~CountValue()
        {
        }
    
        virtual void xparse(boost::any& store, const std::vector<std::string>& /*tokens*/) const
        {
            // Replace the stored value with the access count.
            store = boost::any(++count_);
        }
    
    private:
        mutable std::size_t count_{ 0 };
    };
    
    int main(int argc, char** argv)
    {
        // Define the command line options (we create a new CountValue
        // instance, on the understanding that it will be deleted for us
        // when the options description instance goes out of scope).
        po::options_description options("Options");
        std::size_t verbose = 0;
        options.add_options()
            ("verbose,v", new CountValue(&verbose), "Increase verbosity");
    
        // Parse the command line options.
        po::command_line_parser parser(argc, argv);
        po::variables_map variables;
        po::store(parser.options(options).run(), variables);
        po::notify(variables);
    
        // Show the verbosity level.
        std::cout << "Verbosity " << verbose << "\n";
    }
    

    这使用 C++20 和 Boost 1.77 编译。它正在行动中:

    $ test
    Verbosity 0
    
    $ test -v
    Verbosity 1
    
    $ test -vvv
    Verbosity 3
    
    $ test -v blah blah -v
    Verbosity 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多