代码之家  ›  专栏  ›  技术社区  ›  Sam Miller

分析位置参数

  •  11
  • Sam Miller  · 技术社区  · 14 年前

    examples

    #include <boost/program_options.hpp>
    #include <boost/version.hpp>
    
    #include <iostream>
    
    int
    main( int argc, char** argv )
    {
        namespace po = boost::program_options;
    
        po::options_description desc("Options");
    
        unsigned foo;
        desc.add_options()
            ("help,h", "produce help message")
            ("foo", po::value(&foo), "set foo") 
            ;
    
        po::variables_map vm;
        try {
            po::store(
                    po::parse_command_line( argc, argv, desc ),
                    vm
                    );
            po::notify( vm );
    
            if ( vm.count("help") ) {
                std::cout << desc << "\n";
                std::cout << "boost version: " << BOOST_LIB_VERSION << std::endl;
            }
        } catch ( const boost::program_options::error& e ) {
            std::cerr << e.what() << std::endl;
        }
    }
    

    以下行为符合预期:

    samm$ ./a.out -h
    Options:
      -h [ --help ]         produce help message
      --foo arg             set foo
    
    boost version: 1_44
    samm$ ./a.out --help
    Options:
      -h [ --help ]         produce help message
      --foo arg             set foo
    
    boost version: 1_44
    samm$ ./a.out --foo 1
    samm$ ./a.out --asdf
    unknown option asdf
    samm$
    

    然而,当引入位置参数时,我很惊讶,它没有被标记为错误

    samm$ ./a.out foo bar baz
    samm$
    

    boost::program_options::too_many_positional_options_error 未引发异常?

    1 回复  |  直到 14 年前
        1
  •  15
  •   Sam Miller    14 年前

    当我明确指出不支持位置选项时:

        const po::positional_options_description p; // note empty positional options
        po::store(
                po::command_line_parser( argc, argv).
                          options( desc ).
                          positional( p ).
                          run(),
                          vm
                          );
    

    我得到了预期的行为:

    samm$ ./a.out asdf foo bar
    too many positional options
    samm$