Search code examples
c++boostboost-program-options

Inheriting options with Boost.ProgramOptions


Is there a good way to chain inherit program options from another options_description object in boost? For example

auto general_options = po::options_description{};
general_options.add_options()
   ("flag", "Information for --flag");

auto specific_options_one = po::options_description{};
specific_options.add_options(general_options)
    ("specific_flag_one", "Information for specific flag");

auto specific_options_two = po::options_description{};
specific_options_two.add_options(general_options)
    ("specific_flag_two", "Information for specific flag");

i.e. get the specific_options options instance to use another instance's options along with its own

Such a thing would enable me to specify the --flag option for both the specific_options_one and the specific_options_two instances. For example

./a.out --flag --specific_flag_one
./a.out --flag --specific_flag_two

would both be valid since --flag is inherited


Solution

  • In the Multiple Sources Example from the doc you can see that it is possible to add an option_description to another one, which means you could do something like that:

    auto general_options = po::options_description{};
    general_options.add_options()
       ("flag", "Information for --flag");
    
    auto specific_options_one = po::options_description{};
    specific_options.add(general_options).add_options(general_options)
        ("specific_flag_one", "Information for specific flag");
    
    auto specific_options_two = po::options_description{};
    specific_options_two.add(general_options).add_options(general_options)
        ("specific_flag_two", "Information for specific flag");
    

    Then both specific_options_one and specific_options_two will contain the flags from general_options