boost-program-options: notifier for options with no value

前端 未结 3 446
终归单人心
终归单人心 2020-12-06 04:17

One can use notifier for parsed options only if they have value_semantic. What is the best way for no-value options to be automatically handled by the given notifier?

3条回答
  •  生来不讨喜
    2020-12-06 04:41

    This is full example on providing a flag as an option to complement current answers:

    #include 
    
    #include 
    
    using namespace std;
    
    namespace po = boost::program_options;
    
    
    int main(int ac, char* av[])
    {
        po::options_description desc("Allowed options");
    
        desc.add_options()
            ("help", "produce help message")
            ("overwrite,o", po::bool_switch()->default_value(false),
                            "enable file overwrite");
    
        po::variables_map vm;
        po::store(po::parse_command_line(ac, av, desc), vm);
    
        boolalpha(cout);  // display true and false for bool
        cout << "overwrite is: " << vm["overwrite"].as() << endl;
    
        return 0;
    }
    

    Mine qmake pro file (I use Qt 5.4):

    TEMPLATE = app
    CONFIG += console
    CONFIG += c++14
    CONFIG -= app_bundle
    CONFIG -= qt
    
    SOURCES += main.cpp
    
    
    include(deployment.pri)
    qtcAddDeployment()
    
    INCLUDEPATH += /opt/boost_1_57_0
    
    unix:!macx: LIBS += -L/opt/boost_1_57_0/stage/lib -lboost_program_options
    

    Running the program without any options results in:

    ./untitled4
    overwrite is: false
    

    However running with '-o' option/flag gives:

    ./untitled4 -o
    overwrite is: true
    

提交回复
热议问题