boost::program_options config file option with multiple tokens

前端 未结 3 1486
迷失自我
迷失自我 2021-02-07 10:17

I can not seem to be able to read from config file multitoken options like I can from command line. What is the syntax for the config file?

This is how the option descri

3条回答
  •  半阙折子戏
    2021-02-07 10:29

    You can achieve the behavior you seek by writing a custom validator. This custom validator accepts :

    ./progname --coordinate 1 2
    ./progname --coordinate "1 2"
    #In config file:
    coordinate= 1 2
    

    Here is the code:

    struct coordinate {
      double x,y;
    };
    
    void validate(boost::any& v,
      const vector& values,
      coordinate*, int) {
      coordinate c;
      vector dvalues;
      for(vector::const_iterator it = values.begin();
        it != values.end();
        ++it) {
        stringstream ss(*it);
        copy(istream_iterator(ss), istream_iterator(),
          back_inserter(dvalues));
        if(!ss.eof()) {
          throw po::validation_error("Invalid coordinate specification");
        }
      }
      if(dvalues.size() != 2) {
        throw po::validation_error("Invalid coordinate specification");
      }
      c.x = dvalues[0];
      c.y = dvalues[1];
      v = c;
    }
    ...
        po::options_description config("Configuration");
        config.add_options()
            ("coordinate",po::value()->multitoken(),"Coordinates (x,y)")
            ;
    

    References:

    • http://www.boost.org/doc/libs/1_46_1/doc/html/program_options/howto.html#id2219998
    • https://stackoverflow.com/tags/boost-program-options/hot
    • Handle complex options with Boost's program_options

提交回复
热议问题