Last active
May 17, 2023 09:34
-
-
Save joaomlneto/f29f1eebd01f76bcfb7d56c4b3e5de12 to your computer and use it in GitHub Desktop.
Boost Program Options: ignore undeclared when reading environment variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* When using Boost's program_options to load environment variables, | |
| * there is no way of telling boost to ignore those that were not | |
| * specified in the `options_description` object. | |
| * | |
| * This snippet shows how to get similar behavior to the | |
| * `allow_unregistered()` option available to command line and | |
| * configuration file parsers. | |
| * | |
| * | |
| * For example, if you try to read MYLIB_ONE by specifying an option | |
| * called "one" and using prefix "MYLIB" in `parse_environment`, | |
| * it will work just fine. | |
| * The issue arises if there is another MYLIB_X that wasn't included | |
| * in the `options_description` object. Then an exception will be | |
| * thrown. | |
| * | |
| * If you use the program arguments (argc, argv) or a configuration | |
| * file, there is an option in the library to simply ignore the | |
| * options that weren't declared in the `options_description`. | |
| * For environment variables, that is not the case. | |
| * | |
| * This snippet will simply read the options you declared and will | |
| * ignore any others that may have been declared. | |
| * Thus, behaving like the `allow_unregistered()` functionality. | |
| */ | |
| po::options_description options("My Options"); | |
| lib_options.add_options() | |
| ( | |
| "MY_VAR", | |
| po::value<bool>(&my_var)->default_value(false), | |
| "Dummy boolean test" | |
| ) | |
| ; | |
| po::variables_map env; | |
| po::store(po::parse_environment( | |
| options, | |
| [options](const std::string& var) { | |
| return std::any_of( | |
| options.options().cbegin(), | |
| options.options().cend(), | |
| [var](auto opt) { return var == opt->long_name(); }) ? var : ""; | |
| }), env); | |
| po::notify(env); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment