Program Options
Program Options
Program_options
Vladimir Prus
Copyright 2002-2004 Vladimir Prus Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
Table of Contents
Introduction .......................................................................................................................................................... 2 Tutorial ................................................................................................................................................................ 3 Getting Started .............................................................................................................................................. 3 Option Details ............................................................................................................................................... 4 Multiple Sources ............................................................................................................................................ 6 Library Overview ................................................................................................................................................... 8 Options Description Component ....................................................................................................................... 8 Parsers Component ....................................................................................................................................... 12 Storage Component ...................................................................................................................................... 13 Specic parsers ............................................................................................................................................ 13 Annotated List of Symbols ............................................................................................................................. 14 How To .............................................................................................................................................................. 16 Non-conventional Syntax ............................................................................................................................... 16 Response Files ............................................................................................................................................. 16 Winmain Command Line ............................................................................................................................... 17 Option Groups and Hidden Options ................................................................................................................. 17 Custom Validators ........................................................................................................................................ 19 Unicode Support .......................................................................................................................................... 20 Allowing Unknown Options ........................................................................................................................... 21 Design Discussion ................................................................................................................................................ 22 Unicode Support .......................................................................................................................................... 22 Acknowledgements ............................................................................................................................................... 24 Reference ........................................................................................................................................................... 26 Header <boost/program_options/cmdline.hpp> .................................................................................................. 26 Header <boost/program_options/cong.hpp> ..................................................................................................... 27 Header <boost/program_options/environment_iterator.hpp> ................................................................................. 27 Header <boost/program_options/eof_iterator.hpp> .............................................................................................. 28 Header <boost/program_options/errors.hpp> ..................................................................................................... 30 Header <boost/program_options/option.hpp> ..................................................................................................... 44 Header <boost/program_options/options_description.hpp> ................................................................................... 45 Header <boost/program_options/parsers.hpp> .................................................................................................... 52 Header <boost/program_options/positional_options.hpp> .................................................................................... 60 Header <boost/program_options/value_semantic.hpp> ........................................................................................ 61 Header <boost/program_options/variables_map.hpp> .......................................................................................... 71 Header <boost/program_options/version.hpp> ................................................................................................... 77
Boost.Program_options
Introduction
The program_options library allows program developers to obtain program options, that is (name, value) pairs from the user, via conventional methods such as command line and cong le. Why would you use such a library, and why is it better than parsing your command line by straightforward hand-written code? It's easier. The syntax for declaring options is simple, and the library itself is small. Things like conversion of option values to desired type and storing into program variables are handled automatically. Error reporting is better. All the problems with the command line are reported, while hand-written code can just misparse the input. In addition, the usage message can be automatically generated, to avoid falling out of sync with the real list of options. Options can be read from anywhere. Sooner or later the command line will be not enough for your users, and you'll want cong les or maybe even environment variables. These can be added without signicant effort on your part. Now let's see some examples of the library usage in the the section called Tutorial.
Boost.Program_options
Tutorial
In this section, we'll take a look at the most common usage scenarios of the program_options library, starting with the simplest one. The examples show only the interesting code parts, but the complete programs can be found in the "BOOST_ROOT/libs/program_options/example" directory. Through all the examples, we'll assume that the following namespace alias is in effect:
namespace po = boost::program_options;
Getting Started
The rst example is the simplest possible: it only handles two options. Here's the source code (the full program is in "example/rst.cpp"):
// Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("compression", po::value<int>(), "set compression level") ; po::variables_map vm; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 1; } if (vm.count("compression")) { cout << "Compression level was set to " << vm["compression"].as<int>() << ".\n"; } else { cout << "Compression level was not set.\n"; }
We start by declaring all allowed options using the options_description class. The add_options method of that class returns a special proxy object that denes operator(). Calls to that operator actually declare options. The parameters are option name, information about value, and option description. In this example, the rst option has no value, and the second one has a value of type int. After that, an object of class variables_map is declared. That class is intended to store values of options, and can store values of arbitrary types. Next, the calls to store, parse_command_line and notify functions cause vm to contain all the options found on the command line. And now, nally, we can use the options as we like. The variables_map class can be used just like std::map, except that values stored there must be retrieved with the as method shown above. (If the type specied in the call to the as method is different from the actually stored type, an exception is thrown.) It's now a good time to try compiling the code yourself, but if you're not yet ready, here's an example session:
Boost.Program_options
$ bin/gcc/debug/first Compression level was $ bin/gcc/debug/first Allowed options: --help --compression arg $ bin/gcc/debug/first Compression level was
not set. --help : produce help message : set compression level --compression 10 set to 10.
Option Details
An option value, surely, can have other types than int, and can have other interesting properties, which we'll discuss right now. The complete version of the code snipped below can be found in example/options_description.cpp. Imagine we're writing a compiler. It should take the optimization level, a number of include paths, and a number of input les, and perform some interesting work. Let's describe the options:
int opt; po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("optimization", po::value<int>(&opt)->default_value(10), "optimization level") ("include-path,I", po::value< vector<string> >(), "include path") ("input-file", po::value< vector<string> >(), "input file") ;
The "help" option should be familiar from the previous example. It's a good idea to have this option in all cases. The "optimization" option shows two new features. First, we specify the address of the variable(&opt). After storing values, that variable will have the value of the option. Second, we specify a default value of 10, which will be used if no value is specied by the user. The "include-path" option is an example of the only case where the interface of the options_description class serves only one source -- the command line. Users typically like to use short option names for common options, and the "include-path,I" name species that short option name is "I". So, both "--include-path" and "-I" can be used. Note also that the type of the "include-path" option is std::vector. The library provides special support for vectors -- it will be possible to specify the option several times, and all specied values will be collected in one vector. The "input-le" option species the list of les to process. That's okay for a start, but, of course, writing something like:
compiler --input-file=a.cpp
compiler a.cpp
Boost.Program_options
The command line tokens which have no option name, as above, are called "positional options" by this library. They can be handled too. With a little help from the user, the library can decide that "a.cpp" really means the same as "--input-le=a.cpp". Here's the additional code we need:
po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store(po::command_line_parser(ac, av). options(desc).positional(p).run(), vm); po::notify(vm);
The rst two lines say that all positional options should be translated into "input-le" options. Also note that we use the command_line_parser class to parse the command line, not the parse_command_line function. The latter is a convenient wrapper for simple cases, but now we need to pass additional information. By now, all options are described and parsed. We'll save ourselves the trouble of implementing the rest of the compiler logic and only print the options:
if (vm.count("include-path")) { cout << "Include paths are: " << vm["include-path"].as< vector<string> >() << "\n"; } if (vm.count("input-file")) { cout << "Input files are: " << vm["input-file"].as< vector<string> >() << "\n"; } cout << "Optimization level is " << opt << "\n";
$ bin/gcc/debug/options_description --help Usage: options_description [options] Allowed options: --help : produce help message --optimization arg : optimization level -I [ --include-path ] arg : include path --input-file arg : input file $ bin/gcc/debug/options_description Optimization level is 10 $ bin/gcc/debug/options_description --optimization 4 -I foo a.cpp Include paths are: foo Input files are: a.cpp Optimization level is 4
Oops, there's a slight problem. It's still possible to specify the "--input-le" option, and usage message says so, which can be confusing for the user. It would be nice to hide this information, but let's wait for the next example.
Boost.Program_options
Multiple Sources
It's quite likely that specifying all options to our compiler on the command line will annoy users. What if a user installs a new library and wants to always pass an additional command line element? What if he has made some choices which should be applied on every run? It's desirable to create a cong le with common settings which will be used together with the command line. Of course, there will be a need to combine the values from command line and cong le. For example, the optimization level specied on the command line should override the value from the cong le. On the other hand, include paths should be combined. Let's see the code now. The complete program is in "examples/multiple_sources.cpp". The option denition has two interesting details. First, we declare several instances of the options_description class. The reason is that, in general, not all options are alike. Some options, like "input-le" above, should not be presented in an automatic help message. Some options make sense only in the cong le. Finally, it's nice to have some structure in the help message, not just a long list of options. Let's declare several option groups:
// Declare a group of options that will be // allowed only on command line po::options_description generic("Generic options"); generic.add_options() ("version,v", "print version string") ("help", "produce help message") ; // Declare a group of options that will be // allowed both on command line and in // config file po::options_description config("Configuration"); config.add_options() ("optimization", po::value<int>(&opt)->default_value(10), "optimization level") ("include-path,I", po::value< vector<string> >()->composing(), "include path") ; // Hidden options, will be allowed both on command line and // in config file, but will not be shown to the user. po::options_description hidden("Hidden options"); hidden.add_options() ("input-file", po::value< vector<string> >(), "input file") ;
Note the call to the composing method in the declaration of the "include-path" option. It tells the library that values from different sources should be composed together, as we'll see shortly. The add method of the options_description class can be used to further group the options:
po::options_description cmdline_options; cmdline_options.add(generic).add(config).add(hidden); po::options_description config_file_options; config_file_options.add(config).add(hidden); po::options_description visible("Allowed options"); visible.add(generic).add(config);
Boost.Program_options
The parsing and storing of values follows the usual pattern, except that we additionally call parse_config_file, and call the store function twice. But what happens if the same value is specied both on the command line and in cong le? Usually, the value stored rst is preferred. This is what happens for the "--optimization" option. For "composing" options, like "include-le", the values are merged. Here's an example session:
$ bin/gcc/debug/multiple_sources Include paths are: /opt Optimization level is 1 $ bin/gcc/debug/multiple_sources --help Allows options: Generic options: -v [ --version ] --help
Configuration: --optimization n : optimization level -I [ --include-path ] path : include path $ bin/gcc/debug/multiple_sources --optimization=4 -I foo a.cpp b.cpp Include paths are: foo /opt Input files are: a.cpp b.cpp Optimization level is 4
The rst invocation uses values from the conguration le. The second invocation also uses values from command line. As we see, the include paths on the command line and in the conguration le are merged, while optimization is taken from the command line.
Boost.Program_options
Library Overview
In the tutorial section, we saw several examples of library usage. Here we will describe the overall library design including the primary components and their function. The library has three main components: The options description component, which describes the allowed options and what to do with the values of the options. The parsers component, which uses this information to nd option names and values in the input sources and return them. The storage component, which provides the interface to access the value of an option. It also converts the string representation of values that parsers return into desired C++ types. To be a little more concrete, the options_description class is from the options description component, the parse_command_line function is from the parsers component, and the variables_map class is from the storage component. In the tutorial we've learned how those components can be used by the main function to parse the command line and cong le. Before going into the details of each component, a few notes about the world outside of main. For that outside world, the storage component is the most important. It provides a class which stores all option values and that class can be freely passed around your program to modules which need access to the options. All the other components can be used only in the place where the actual parsing is the done. However, it might also make sense for the individual program modules to describe their options and pass them to the main module, which will merge all options. Of course, this is only important when the number of options is large and declaring them in one place becomes troublesome.
options_description desc; desc.add_options() ("help", "produce help") ("optimization", value<int>()->default_value(10), "optimization level") ;
The call to the value function creates an instance of a class derived from the value_semantic class: typed_value. That class contains the code to parse values of a specic type, and contains a number of methods which can be called by the user to specify additional information. (This essentially emulates named parameters of the constructor.) Calls to operator() on the object returned by add_options forward arguments to the constructor of the option_description class and add the new instance. Note that in addition to the value, library provides the bool_switch function, and user can write his own function which will return other subclasses of value_semantic with different behaviour. For the remainder of this section, we'll talk only about the value function. The information about an option is divided into syntactic and semantic. Syntactic information includes the name of the option and the number of tokens which can be used to specify the value. This information is used by parsers to group tokens into (name, value) pairs, where value is just a vector of strings (std::vector<std::string>). The semantic layer is responsible for converting the value of the option into more usable C++ types.
Boost.Program_options
This separation is an important part of library design. The parsers use only the syntactic layer, which takes away some of the freedom to use overly complex structures. For example, it's not easy to parse syntax like:
calc --expression=1 + 2/3
without knowing that it's a C expression. With a little help from the user the task becomes trivial, and the syntax clear:
calc --expression="1 + 2/3"
Syntactic Information
The syntactic information is provided by the boost::program_options::options_description class and some methods of the boost::program_options::value_semantic class and includes: name of the option, used to identify the option inside the program, description of the option, which can be presented to the user, the allowed number of source tokens that comprise options's value, which is used during parsing. Consider the following example:
options_description desc; desc.add_options() ("help", "produce help message") ("compression", value<string>(), "compression level") ("verbose", value<string>()->implicit_value("0"), "verbosity level") ("email", value<string>()->multitoken(), "email to send to") ;
For the rst parameter, we specify only the name and the description. No value can be specied in the parsed source. For the rst option, the user must specify a value, using a single token. For the third option, the user may either provide a single token for the value, or no token at all. For the last option, the value can span several tokens. For example, the following command line is OK:
Description formatting
Sometimes the description can get rather long, for example, when several option's values need separate documentation. Below we describe some simple formatting mechanisms you can use. The description string has one or more paragraphs, separated by the newline character ('\n'). When an option is output, the library will compute the indentation for options's description. Each of the paragraph is output as a separate line with that intentation. If a paragraph does not t on one line it is spanned over multiple lines (which will have the same indentation). You may specify additional indent for the rst specied by inserting spaces at the beginning of a paragraph. For example:
Boost.Program_options
options.add_options() ("help", " A long help msg a long help msg a long help msg a long help msg a long help msg a long help msg a long help msg a long help msg ") ;
will specify a four-space indent for the rst line. The output will look like:
--help
A long help help msg a long a long help msg help msg a long a long help msg help msg
For the case where line is wrapped, you can want an additional indent for wrapped text. This can be done by inserting a tabulator character ('\t') at the desired position. For example:
options.add_options() ("well_formated", "As you can see this is a very well formatted option description.\n" "You can do this for example:\n\n" "Values:\n" " Value1: \tdoes this and that, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla\n" " Value2: \tdoes something else, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla\n\n" " This paragraph has a first line indent only, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla");
will produce:
10
Boost.Program_options
--well_formated
As you can see this is a very well formatted option description. You can do this for example: Values: Value1: does this and that, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla Value2: does something else, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla This paragraph has a first line indent only, bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla
The tab character is removed before output. Only one tabulator per paragraph is allowed, otherwisee an exception of type program_options::error is thrown. Finally, the tabulator is ignored if it's is not on the rst line of the paragraph or is on the last possible position of the rst line.
Semantic Information
The semantic information is completely provided by the boost::program_options::value_semantic class. For example:
options_description desc; desc.add_options() ("compression", value<int>()->default_value(10), "compression level") ("email", value< vector<string> >() ->composing()->notifier(&your_function), "email") ;
These declarations specify that default value of the rst option is 10, that the second option can appear several times and all instances should be merged, and that after parsing is done, the library will call function &your_function, passing the value of the "email" option as argument.
Positional Options
Our denition of option as (name, value) pairs is simple and useful, but in one special case of the command line, there's a problem. A command line can include a positional option, which does not specify any name at all, for example:
Here, the "/etc/passwd" element does not have any option name.
11
Boost.Program_options
One solution is to ask the user to extract positional options himself and process them as he likes. However, there's a nicer approach -- provide a method to automatically assign the names for positional options, so that the above command line can be interpreted the same way as:
The positional_options_description class allows the command line parser to assign the names. The class species how many positional options are allowed, and for each allowed option, species the name. For example:
species that for exactly one, rst, positional option the name will be "input-le". It's possible to specify that a number, or even all positional options, be given the same name.
In the above example, the rst two positional options will be associated with name "output-le", and any others with the name "inputle".
Warning
The positional_options_description class only species translation from position to name, and the option name should still be registered with an instance of the options_description class.
Parsers Component
The parsers component splits input sources into (name, value) pairs. Each parser looks for possible options and consults the options description component to determine if the option is known and how its value is specied. In the simplest case, the name is explicitly specied, which allows the library to decide if such option is known. If it is known, the value_semantic instance determines how the value is specied. (If it is not known, an exception is thrown.) Common cases are when the value is explicitly specied by the user, and when the value cannot be specied by the user, but the presence of the option implies some value (for example, true). So, the parser checks that the value is specied when needed and not specied when not needed, and returns new (name, value) pair. To invoke a parser you typically call a function, passing the options description and command line or cong le or something else. The results of parsing are returned as an instance of the parsed_options class. Typically, that object is passed directly to the storage component. However, it also can be used directly, or undergo some additional processing. There are three exceptions to the above model -- all related to traditional usage of the command line. While they require some support from the options description component, the additional complexity is tolerable. The name specied on the command line may be different from the option name -- it's common to provide a "short option name" alias to a longer name. It's also common to allow an abbreviated name to be specied on the command line. Sometimes it's desirable to specify value as several tokens. For example, an option "--email-recipient" may be followed by several emails, each as a separate command line token. This behaviour is supported, though it can lead to parsing ambiguities and is not enabled by default. The command line may contain positional options -- elements which don't have any name. The command line parser provides a mechanism to guess names for such options, as we've seen in the tutorial.
12
Boost.Program_options
Storage Component
The storage component is responsible for: Storing the nal values of an option into a special class and in regular variables Handling priorities among different sources. Calling user-specied notify functions with the nal values of options. Let's consider an example:
variables_map vm; store(parse_command_line(argc, argv, desc), vm); store(parse_config_file("example.cfg", desc), vm); notify(vm);
The variables_map class is used to store the option values. The two calls to the store function add values found on the command line and in the cong le. Finally the call to the notify function runs the user-specied notify functions and stores the values into regular variables, if needed. The priority is handled in a simple way: the store function will not change the value of an option if it's already assigned. In this case, if the command line species the value for an option, any value in the cong le is ignored.
Warning
Don't forget to call the notify function after you've stored all parsed values.
Specific parsers
Configuration file parser
The parse_config_file function implements parsing of simple INI-like conguration les. Conguration le syntax is line based: A line in the form:
name=value
[section name]
introduces a new section in the conguration le. The # character introduces a comment that spans until the end of the line. The option names are relative to the section names, so the following conguration le part:
13
Boost.Program_options
[gui.accessibility] visual_bell=yes
is equivalent to
gui.accessibility.visual_bell=yes
14
Boost.Program_options
Description
Parsers component
parse_command_line basic_command_line_parser parse_config_file parse_environment
parses command line (simpied interface) parses command line (extended interface) parses cong le parses environment
Storage component
variables_map
15
Boost.Program_options
How To
This section describes how the library can be used in specic situations.
Non-conventional Syntax
Sometimes, standard command line syntaxes are not enough. For example, the gcc compiler has "-frtti" and -fno-rtti" options, and this syntax is not directly supported. For such cases, the library allows the user to provide an additional parser -- a function which will be called on each command line element, before any processing by the library. If the additional parser recognises the syntax, it returns the option name and value, which are used directly. The above example can be handled by the following code:
pair<string, string> reg_foo(const string& s) { if (s.find("-f") == 0) { if (s.substr(2, 3) == "no-") return make_pair(s.substr(5), string("false")); else return make_pair(s.substr(2), string("true")); } else { return make_pair(string(), string()); } }
Here's the denition of the additional parser. When parsing the command line, we pass the additional parser:
Response Files
Some operating system have very low limits of the command line length. The common way to work around those limitations is using response les. A response le is just a conguration le which uses the same syntax as the command line. If the command line species a name of response le to use, it's loaded and parsed in addition to the command line. The library does not provide direct support for response les, so you'll need to write some extra code. First, you need to dene an option for the response le:
Second, you'll need an additional parser to support the standard syntax for specifying response les: "@le":
16
Boost.Program_options
pair<string, string> at_option_parser(string const&s) { if ('@' == s[0]) return std::make_pair(string("response-file"), s.substr(1)); else return pair<string, string>(); }
Finally, when the "response-le" option is found, you'll have to load that le and pass it to the command line parser. This part is the hardest. We'll use the Boost.Tokenizer library, which works but has some limitations. You might also consider Boost.StringAlgo. The code is:
if (vm.count("response-file")) { // Load the file and tokenize it ifstream ifs(vm["response-file"].as<string>().c_str()); if (!ifs) { cout << "Could not open the response file\n"; return 1; } // Read the whole file into a string stringstream ss; ss << ifs.rdbuf(); // Split the file content char_separator<char> sep(" \n\r"); std::string ResponsefileContents( ss.str() ); tokenizer<char_separator<char> > tok(ResponsefileContents, sep); vector<string> args; copy(tok.begin(), tok.end(), back_inserter(args)); // Parse the file and store the options store(command_line_parser(args).options(desc).run(), vm); }
The split_winmain function is overloaded for wchar_t strings, so can also be used in Unicode applications.
17
Boost.Program_options
The user would prefer some structure in the generated help message. Some options shouldn't appear in the generated help message at all. To solve the above issues, the library allows a programmer to create several instances of the options_description class, which can be merged in different combinations. The following example will dene three groups of options: command line specic, and two options group for specic program modules, only one of which is shown in the generated help message. Each group is dened using standard syntax. However, you should use reasonable names for each options_description instance:
options_description general("General options"); general.add_options() ("help", "produce a help message") ("help-module", value<string>(), "produce a help for a given module") ("version", "output the version number") ; options_description gui("GUI options"); gui.add_options() ("display", value<string>(), "display to use") ; options_description backend("Backend options"); backend.add_options() ("num-threads", value<int>(), "the initial number of threads") ;
After declaring options groups, we merge them in two combinations. The rst will include all options and be used for parsing. The second will be used for the "--help" option.
// Declare an options description instance which will include // all the options options_description all("Allowed options"); all.add(general).add(gui).add(backend); // Declare an options description instance which will be shown // to the user options_description visible("Allowed options"); visible.add(general).add(gui);
18
Boost.Program_options
variables_map vm; store(parse_command_line(ac, av, all), vm); if (vm.count("help")) { cout << visible; return 0; } if (vm.count("help-module")) { const string& s = vm["help-module"].as<string>(); if (s == "gui") { cout << gui; } else if (s == "backend") { cout << backend; } else { cout << "Unknown module '" << s << "' in the --help-module option\n"; return 1; } return 0; } if (vm.count("num-threads")) { cout << "The 'num-threads' options was set to " << vm["num-threads"].as<int>() << "\n"; }
When parsing the command line, all options are allowed. The "--help" message, however, does not include the "Backend options" group -- the options in that group are hidden. The user can explicitly force the display of that options group by passing "--helpmodule backend" option. The complete example can be found in the "example/option_groups.cpp" le.
Custom Validators
By default, the conversion of option's value from string into C++ type is done using iostreams, which sometimes is not convenient. The library allows the user to customize the conversion for specic classes. In order to do so, the user should provide suitable overload of the validate function. Let's rst dene a simple class:
19
Boost.Program_options
void validate(boost::any& v, const std::vector<std::string>& values, magic_number* target_type, int) { static regex r("\\d\\d\\d-(\\d\\d\\d)"); using namespace boost::program_options; // Make sure no previous assignment to 'a' was made. validators::check_first_occurrence(v); // Extract the first string from 'values'. If there is more than // one string, it's an error, and exception will be thrown. const string& s = validators::get_single_string(values); // Do regex match and convert the interesting part to // int. smatch match; if (regex_match(s, match, r)) { v = any(magic_number(lexical_cast<int>(match[1]))); } else { throw validation_error(validation_error::invalid_option_value); } }
The function takes four parameters. The rst is the storage for the value, and in this case is either empty or contains an instance of the magic_number class. The second is the list of strings found in the next occurrence of the option. The remaining two parameters are needed to workaround the lack of partial template specialization and partial function template ordering on some compilers. The function rst checks that we don't try to assign to the same option twice. Then it checks that only a single string was passed in. Next the string is veried with the help of the Boost.Regex library. If that test is passed, the parsed value is stored into the v variable. The complete example can be found in the "example/regex.cpp" le.
Unicode Support
To use the library with Unicode, you'd need to: Use Unicode-aware parsers for Unicode input Require Unicode support for options which need it Most of the parsers have Unicode versions. For example, the parse_command_line function has an overload which takes wchar_t strings, instead of ordinary char. Even if some of the parsers are Unicode-aware, it does not mean you need to change denition of all the options. In fact, for many options, like integer ones, it makes no sense. To make use of Unicode you'll need some Unicode-aware options. They are different from ordinary options in that they accept wstring input, and process it using wide character streams. Creating an Unicode-aware option is easy: just use the the wvalue function instead of the regular value. When an ascii parser passes data to an ascii option, or a Unicode parser passes data to a Unicode option, the data are not changed at all. So, the ascii option will see a string in local 8-bit encoding, and the Unicode option will see whatever string was passed as the Unicode input. What happens when Unicode data is passed to an ascii option, and vice versa? The library automatically performs the conversion from Unicode to local 8-bit encoding. For example, if command line is in ascii, but you use wstring options, then the ascii input will be converted into Unicode.
20
Boost.Program_options
To perform the conversion, the library uses the codecvt<wchar_t, char> locale facet from the global locale. If you want to work with strings that use local 8-bit encoding (as opposed to 7-bit ascii subset), your application should start with:
locale::global(locale(""));
which would set up the conversion facet according to the user's selected locale. It's wise to check the status of the C++ locale support on your implementation, though. The quick test involves three steps: 1. Go the the "test" directory and build the "test_convert" binary. 2. Set some non-ascii locale in the environmemt. On Linux, one can run, for example:
$ export LC_CTYPE=ru_RU.KOI8-R
3. Run the "test_convert" binary with any non-ascii string in the selected encoding as its parameter. If you see a list of Unicode codepoints, everything's OK. Otherwise, locale support on your system might be broken.
For each token that looks like an option, but does not have a known name, an instance of basic_option will be added to the result. The string_key and value elds of the instance will contain results of syntactic parsing of the token, the unregistered eld will be set to true, and the original_tokens eld will contain the token as it appeared on the command line. If you want to pass the unrecognized options further, the collect_unrecognized function can be used. The function will collect original tokens for all unrecognized values, and optionally, all found positional options. Say, if your code handles a few options, but does not handles positional options at all, you can use the function like this:
21
Boost.Program_options
Design Discussion
This section focuses on some of the design questions.
Unicode Support
Unicode support was one of the features specically requested during the formal review. Throughout this document "Unicode support" is a synonym for "wchar_t" support, assuming that "wchar_t" always uses Unicode encoding. Also, when talking about "ascii" (in lowercase) we'll not mean strict 7-bit ASCII encoding, but rather "char" strings in local 8-bit encoding. Generally, "Unicode support" can mean many things, but for the program_options library it means that: Each parser should accept either char* or wchar_t*, correctly split the input into option names and option values and return the data. For each option, it should be possible to specify whether the conversion from string to value uses ascii or Unicode. The library guarantees that: ascii input is passed to an ascii value without change Unicode input is passed to a Unicode value without change ascii input passed to a Unicode value, and Unicode input passed to an ascii value will be converted using a codecvt facet (which may be specied by the user). The important point is that it's possible to have some "ascii options" together with "Unicode options". There are two reasons for this. First, for a given type you might not have the code to extract the value from Unicode string and it's not good to require that such code be written. Second, imagine a reusable library which has some options and exposes options description in its interface. If all options are either ascii or Unicode, and the library does not use any Unicode strings, then the author will likely to use ascii options, which would make the library unusable inside Unicode applications. Essentially, it would be necessary to provide two versions of the library -- ascii and Unicode. Another important point is that ascii strings are passed though without modication. In other words, it's not possible to just convert ascii to Unicode and process the Unicode further. The problem is that the default conversion mechanism -- the codecvt facet -might not work with 8-bit input without additional setup. The Unicode support outlined above is not complete. For example, we don't support Unicode option names. Unicode support is hard and requires a Boost-wide solution. Even comparing two arbitrary Unicode strings is non-trivial. Finally, using Unicode in option names is related to internationalization, which has it's own complexities. E.g. if option names depend on current locale, then all program parts and other parts which use the name must be internationalized too. The primary question in implementing the Unicode support is whether to use templates and std::basic_string or to use some internal encoding and convert between internal and external encodings on the interface boundaries. The choice, mostly, is between code size and execution speed. A templated solution would either link library code into every application that uses the library (thereby making shared library impossible), or provide explicit instantiations in the shared library (increasing its size). The solution based on internal encoding would necessarily make conversions in a number of places and will be somewhat slower. Since speed is generally not an issue for this library, the second solution looks more attractive, but we'll take a closer look at individual components. For the parsers component, we have three choices: Use a fully templated implementation: given a string of a certain type, a parser will return a parsed_options instance with strings of the same type (i.e. the parsed_options class will be templated). Use internal encoding: same as above, but strings will be converted to and from the internal encoding.
22
Boost.Program_options
Use and partly expose the internal encoding: same as above, but the strings in the parsed_options instance will be in the internal encoding. This might avoid a conversion if parsed_options instance is passed directly to other components, but can be also dangerous or confusing for a user. The second solution appears to be the best -- it does not increase the code size much and is cleaner than the third. To avoid extra conversions, the Unicode version of parsed_options can also store strings in internal encoding. For the options descriptions component, we don't have much choice. Since it's not desirable to have either all options use ascii or all of them use Unicode, but rather have some ascii and some Unicode options, the interface of the value_semantic must work with both. The only way is to pass an additional ag telling if strings use ascii or internal encoding. The instance of value_semantic can then convert into some other encoding if needed. For the storage component, the only affected function is store. For Unicode input, the store function should convert the value to the internal encoding. It should also inform the value_semantic class about the used encoding. Finally, what internal encoding should we use? The alternatives are: std::wstring (using UCS-4 encoding) and std::string (using UTF-8 encoding). The difference between alternatives is: Speed: UTF-8 is a bit slower Space: UTF-8 takes less space when input is ascii Code size: UTF-8 requires additional conversion code. However, it allows one to use existing parsers without converting them to std::wstring and such conversion is likely to create a number of new instantiations. There's no clear leader, but the last point seems important, so UTF-8 will be used. Choosing the UTF-8 encoding allows the use of existing parsers, because 7-bit ascii characters retain their values in UTF-8, so searching for 7-bit strings is simple. However, there are two subtle issues: We need to assume the character literals use ascii encoding and that inputs use Unicode encoding. A Unicode character (say '=') can be followed by 'composing character' and the combination is not the same as just '=', so a simple search for '=' might nd the wrong character. Neither of these issues appear to be critical in practice, since ascii is almost universal encoding and since composing characters following '=' (and other characters with special meaning to the library) are not likely to appear.
23
Boost.Program_options
Acknowledgements
I'm very gratefull to all the people who helped with the development, by discussion, xes, and as users. It was pleasant to see all that involvement, which made the library much better than it would be otherwise. In the early stages, the library was affected by discussions with Gennadiy Rozental, William Kempf and Alexander Okhotin. Hartmut Kaiser was the rst person to try the library on his project and send a number of suggestions and xes. The formal review lead to numerous comments and enhancements. Pavol Droba helped with the option description semantic. Gennadiy Rozental has criticised many aspects of the library which caused various simplications. Pavel Vozenilek did carefull review of the implementation. A number of comments were made by: David Abrahams Neal D. Becker Misha Bergal James Curran Carl Daniel Beman Dawes Tanton Gibbs Holger Grund Hartmut Kaiser Petr Kocmid Baptiste Lepilleur Marcelo E. Magallon Chuck Messenger John Torjo Matthias Troyer Doug Gregor and Reece Dunn helped to resolve the issues with Boostbook version of the documentation. Even after review, a number of people have helped with further development: Rob Lievaart Thorsten Ottosen Joseph Wu Ferdinand Prantl Miro Jurisic John Maddock Janusz Piwowarski
24
Boost.Program_options
25
Boost.Program_options
Reference
Header <boost/program_options/cmdline.hpp>
namespace boost { namespace program_options { namespace command_line_style { enum style_t; } } }
Type style_t
boost::program_options::command_line_style::style_t
Synopsis
// In header: <boost/program_options/cmdline.hpp>
enum style_t { allow_long = = 1, allow_short = = allow_long << 1, allow_dash_for_short = = allow_short << 1, allow_slash_for_short = = allow_dash_for_short << 1, long_allow_adjacent = = allow_slash_for_short << 1, long_allow_next = = long_allow_adjacent << 1, short_allow_adjacent = = long_allow_next << 1, short_allow_next = = short_allow_adjacent << 1, allow_sticky = = short_allow_next << 1, allow_guessing = = allow_sticky << 1, long_case_insensitive = = allow_guessing << 1, short_case_insensitive = = long_case_insensitive << 1, case_insensitive = = (long_case_insensitive | short_case_insensitive), allow_long_disguise = = short_case_insensitive << 1, unix_style = = (allow_short | short_allow_adjacent | short_allow_next | allow_long | long_allow_adjacent | long_allow_next | allow_sticky | allow_guessing | allow_dash_for_short), default_style = = unix_style };
Description
Various possible styles of options. There are "long" options, which start with "–" and "short", which start with either "-" or "/". Both kinds can be allowed or disallowed, see allow_long and allow_short. The allowed character for short options is also congurable. Option's value can be specied in the same token as name ("–foo=bar"), or in the next token. It's possible to introduce long options by the same character as short options, see allow_long_disguise. Finally, guessing (specifying only prex of option) and case insensitive processing are supported.
allow_long allow_short allow_dash_for_short allow_slash_for_short
Allow "–long_name" style. Allow "-<single character" style. Allow "-" in short options. Allow "/" in short options.
26
Boost.Program_options
Allow option parameter in the same token for long option, like in --foo=10 Allow option parameter in the next token for long options. Allow option parameter in the same token for short options. Allow option parameter in the next token for short options. Allow to merge several short options together, so that "-s -k" become "-sk". All of the options but last should accept no parameter. For example, if "-s" accept a parameter, then "k" will be taken as parameter, not another short option. Dos-style short options cannot be sticky. Allow abbreviated spellings for long options, if they unambiguously identify long option. No long option name should be prex of other long option name if guessing is in effect. Ignore the difference in case for long options. Ignore the difference in case for short options. Ignore the difference in case for all options. Allow long options with single option starting character, e.g -foo=10 The more-or-less traditional unix style. The default style.
Header <boost/program_options/config.hpp>
BOOST_PROGRAM_OPTIONS_DECL
Macro BOOST_PROGRAM_OPTIONS_DECL
BOOST_PROGRAM_OPTIONS_DECL
Synopsis
// In header: <boost/program_options/config.hpp> BOOST_PROGRAM_OPTIONS_DECL
Header <boost/program_options/environment_iterator.hpp>
namespace boost { class environment_iterator; }
Class environment_iterator
boost::environment_iterator
27
Boost.Program_options
Synopsis
// In header: <boost/program_options/environment_iterator.hpp> class environment_iterator : public boost::eof_iterator< environment_iterator, std::pair< std::string, std::string > > { public: // construct/copy/destruct environment_iterator(char **); environment_iterator(); // public member functions void get(); };
Description
environment_iterator public construct/copy/destruct
1.
environment_iterator(char ** environment);
2.
environment_iterator();
1.
void get();
Header <boost/program_options/eof_iterator.hpp>
namespace boost { template<typename Derived, typename ValueType> class eof_iterator; }
28
Boost.Program_options
Synopsis
// In header: <boost/program_options/eof_iterator.hpp> template<typename Derived, typename ValueType> class eof_iterator : public iterator_facade< Derived, const ValueType, forward_traversal_tag > { public: // construct/copy/destruct eof_iterator(); // protected member functions ValueType & value(); void found_eof(); // private member functions void increment(); bool equal(const eof_iterator &) const; const ValueType & dereference() const; };
Description
The 'eof_iterator' class is useful for constructing forward iterators in cases where iterator extract data from some source and it's easy to detect 'eof' <ndash></ndash> i.e. the situation where there's no data. One apparent example is reading lines from a le. Implementing such iterators using 'iterator_facade' directly would require to create class with three core operation, a couple of constructors. When using 'eof_iterator', the derived class should dene only one method to get new value, plus a couple of constructors. The basic idea is that iterator has 'eof' bit. Two iterators are equal only if both have their 'eof' bits set. The 'get' method either obtains the new value or sets the 'eof' bit. Specically, derived class should dene: 1. A default constructor, which creates iterator with 'eof' bit set. The constructor body should call 'found_eof' method dened here. 2. Some other constructor. It should initialize some 'data pointer' used in iterator operation and then call 'get'. 3. The 'get' method. It should operate this way: look at some 'data pointer' to see if new element is available; if not, it should call 'found_eof'. extract new element and store it at location returned by the 'value' method. advance the data pointer. Essentially, the 'get' method has the functionality of both 'increment' and 'dereference'. It's very good for the cases where data extraction implicitly moves data pointer, like for stream operation.
eof_iterator public construct/copy/destruct
1.
eof_iterator();
29
Boost.Program_options
1.
Returns the reference which should be used by derived class to store the next value. 2.
void found_eof();
Should be called by derived class to indicate that it can't produce next element.
eof_iterator private member functions
1.
void increment();
2.
3.
Header <boost/program_options/errors.hpp>
namespace boost { namespace program_options { class error; class too_many_positional_options_error; class invalid_command_line_style; class reading_file; class error_with_option_name; class multiple_values; class multiple_occurrences; class required_option; class error_with_no_option_name; class unknown_option; class ambiguous_option; class invalid_syntax; class invalid_config_file_syntax; class invalid_command_line_syntax; class validation_error; class invalid_option_value; class invalid_bool_value; std::string strip_prefixes(const std::string & text); } }
Class error
boost::program_options::error
30
Boost.Program_options
Synopsis
// In header: <boost/program_options/errors.hpp>
Description
Base class for all errors in the library.
error public construct/copy/destruct
1.
Class too_many_positional_options_error
boost::program_options::too_many_positional_options_error
Synopsis
// In header: <boost/program_options/errors.hpp>
Description
Class thrown when there are too many positional options. This is a programming error.
too_many_positional_options_error public construct/copy/destruct
1.
too_many_positional_options_error();
Class invalid_command_line_style
boost::program_options::invalid_command_line_style
31
Boost.Program_options
Synopsis
// In header: <boost/program_options/errors.hpp>
Description
Class thrown when there are programming error related to style
invalid_command_line_style public construct/copy/destruct
1.
Class reading_file
boost::program_options::reading_le
Synopsis
// In header: <boost/program_options/errors.hpp>
Description
Class thrown if cong le can not be read
reading_file public construct/copy/destruct
1.
Class error_with_option_name
boost::program_options::error_with_option_name
32
Boost.Program_options
Synopsis
// In header: <boost/program_options/errors.hpp>
class error_with_option_name : public boost::program_options::error { public: // construct/copy/destruct error_with_option_name(const std::string &, const std::string & = "", const std::string & = "", int = 0); ~error_with_option_name(); // public member functions void set_substitute(const std::string &, const std::string &); void set_substitute_default(const std::string &, const std::string &, const std::string &); void add_context(const std::string &, const std::string &, int); void set_prefix(int); void set_option_name(const std::string &); std::string get_option_name() const; void set_original_token(const std::string &); const char * what() const; // protected member functions void substitute_placeholders(const std::string &) const; void replace_token(const std::string &, const std::string &) const; std::string get_canonical_option_name() const; std::string get_canonical_option_prefix() const; // public data members std::string m_error_template; };
Description
Base class for most exceptions in the library. Substitutes the values for the parameter name placeholders in the template to create the human readable error message Placeholders are surrounded by % signs: example% Poor man's version of boost::format If a parameter name is absent, perform default substitutions instead so ugly placeholders are never left in-place. Options are displayed in "canonical" form This is the most unambiguous form of the parsed option name and would correspond to option_description::format_name() i.e. what is shown by print_usage() The "canonical" form depends on whether the option is specied in short or long form, using dashes or slashes or without a prex (from a conguration le)
error_with_option_name public construct/copy/destruct
1.
error_with_option_name(const std::string & template_, const std::string & option_name = "", const std::string & original_token = "", int option_style = 0);
2.
~error_with_option_name();
33
Boost.Program_options
gcc says that throw specication on dtor is loosened without this line
error_with_option_name public member functions
1.
Substitute parameter_name->value to create the error message from the error template 2.
void set_substitute_default(const std::string & parameter_name, const std::string & from, const std::string & to);
5.
Overridden in error_with_no_option_name 6.
std::string get_option_name() const;
7.
8.
1.
3.
Construct option name in accordance with the appropriate prex style: i.e. long dash or short slash etc 4.
std::string get_canonical_option_prefix() const;
34
Boost.Program_options
1.
std::string m_error_template;
Class multiple_values
boost::program_options::multiple_values
Synopsis
// In header: <boost/program_options/errors.hpp>
Description
Class thrown when there are several option values, but user called a method which cannot return them all.
multiple_values public construct/copy/destruct
1.
multiple_values();
2.
~multiple_values();
Class multiple_occurrences
boost::program_options::multiple_occurrences
Synopsis
// In header: <boost/program_options/errors.hpp>
35
Boost.Program_options
Description
Class thrown when there are several occurrences of an option, but user called a method which cannot return them all.
multiple_occurrences public construct/copy/destruct
1.
multiple_occurrences();
2.
~multiple_occurrences();
Class required_option
boost::program_options::required_option
Synopsis
// In header: <boost/program_options/errors.hpp>
class required_option : public boost::program_options::error_with_option_name { public: // construct/copy/destruct required_option(const std::string &); ~required_option(); };
Description
Class thrown when a required/mandatory option is missing
required_option public construct/copy/destruct
1.
2.
~required_option();
Class error_with_no_option_name
boost::program_options::error_with_no_option_name
36
Boost.Program_options
Synopsis
// In header: <boost/program_options/errors.hpp>
class error_with_no_option_name : public boost::program_options::error_with_option_name { public: // construct/copy/destruct error_with_no_option_name(const std::string &, const std::string & = ""); ~error_with_no_option_name(); // public member functions void set_option_name(const std::string &); };
Description
Base class of unparsable options, when the desired option cannot be identied. It makes no sense to have an option name, when we can't match an option to the parameter Having this a part of the error_with_option_name hierachy makes error handling a lot easier, even if the name indicates some sort of conceptual dissonance!
error_with_no_option_name public construct/copy/destruct
1.
2.
~error_with_no_option_name();
1.
Does NOT set option name, because no option name makes sense
Class unknown_option
boost::program_options::unknown_option
37
Boost.Program_options
Synopsis
// In header: <boost/program_options/errors.hpp>
class unknown_option : public boost::program_options::error_with_no_option_name { public: // construct/copy/destruct unknown_option(const std::string & = ""); ~unknown_option(); };
Description
Class thrown when option name is not recognized.
unknown_option public construct/copy/destruct
1.
2.
~unknown_option();
Class ambiguous_option
boost::program_options::ambiguous_option
Synopsis
// In header: <boost/program_options/errors.hpp>
class ambiguous_option : public boost::program_options::error_with_no_option_name { public: // construct/copy/destruct ambiguous_option(const std::vector< std::string > &); ~ambiguous_option(); // public member functions const std::vector< std::string > & alternatives() const; // protected member functions void substitute_placeholders(const std::string &) const; };
Description
Class thrown when there's ambiguity amoung several possible options.
38
Boost.Program_options
1.
2.
~ambiguous_option();
1.
1.
Class invalid_syntax
boost::program_options::invalid_syntax
Synopsis
// In header: <boost/program_options/errors.hpp>
class invalid_syntax : public boost::program_options::error_with_option_name { public: enum kind_t { long_not_allowed = = 30, long_adjacent_not_allowed, short_adjacent_not_allowed, empty_adjacent_parameter, missing_parameter, extra_parameter, unrecognized_line }; // construct/copy/destruct invalid_syntax(kind_t, const std::string & = "", const std::string & = "", int = 0); ~invalid_syntax(); // public member functions kind_t kind() const; std::string tokens() const; // protected member functions std::string get_template(kind_t); };
Description
Class thrown when there's syntax error either for command line or cong le options. See derived children for concrete classes.
invalid_syntax public construct/copy/destruct
1.
invalid_syntax(kind_t kind, const std::string & option_name = "", const std::string & original_token = "", int option_style = 0);
39
Boost.Program_options
2.
~invalid_syntax();
1.
2.
1.
Class invalid_config_file_syntax
boost::program_options::invalid_cong_le_syntax
Synopsis
// In header: <boost/program_options/errors.hpp>
class invalid_config_file_syntax : public boost::program_options::invalid_syntax { public: // construct/copy/destruct invalid_config_file_syntax(const std::string &, kind_t); ~invalid_config_file_syntax(); // public member functions std::string tokens() const; };
Description
invalid_config_file_syntax public construct/copy/destruct
1.
2.
~invalid_config_file_syntax();
1.
40
Boost.Program_options
Class invalid_command_line_syntax
boost::program_options::invalid_command_line_syntax
Synopsis
// In header: <boost/program_options/errors.hpp>
class invalid_command_line_syntax : public boost::program_options::invalid_syntax { public: // construct/copy/destruct invalid_command_line_syntax(kind_t, const std::string & = "", const std::string & = "", int = 0); ~invalid_command_line_syntax(); };
Description
Class thrown when there are syntax errors in given command line
invalid_command_line_syntax public construct/copy/destruct
1.
invalid_command_line_syntax(kind_t kind, const std::string & option_name = "", const std::string & original_token = "", int option_style = 0);
2.
~invalid_command_line_syntax();
Class validation_error
boost::program_options::validation_error
41
Boost.Program_options
Synopsis
// In header: <boost/program_options/errors.hpp>
class validation_error : public boost::program_options::error_with_option_name { public: enum kind_t { multiple_values_not_allowed = = 30, at_least_one_value_required, invalid_bool_value, invalid_option_value, invalid_option }; // construct/copy/destruct validation_error(kind_t, const std::string & = "", const std::string & = "", int = 0); ~validation_error(); // protected member functions std::string get_template(kind_t); };
Description
Class thrown when value of option is incorrect.
validation_error public construct/copy/destruct
1.
validation_error(kind_t kind, const std::string & option_name = "", const std::string & original_token = "", int option_style = 0);
2.
~validation_error();
1.
Class invalid_option_value
boost::program_options::invalid_option_value
42
Boost.Program_options
Synopsis
// In header: <boost/program_options/errors.hpp>
class invalid_option_value : public boost::program_options::validation_error { public: // construct/copy/destruct invalid_option_value(const std::string &); invalid_option_value(const std::wstring &); };
Description
Class thrown if there is an invalid option value given
invalid_option_value public construct/copy/destruct
1.
2.
Class invalid_bool_value
boost::program_options::invalid_bool_value
Synopsis
// In header: <boost/program_options/errors.hpp>
Description
Class thrown if there is an invalid bool value given
invalid_bool_value public construct/copy/destruct
1.
43
Boost.Program_options
Header <boost/program_options/option.hpp>
namespace boost { namespace program_options { template<typename charT> class basic_option; typedef basic_option< char > option; typedef basic_option< wchar_t > woption; } }
Synopsis
// In header: <boost/program_options/option.hpp> template<typename charT> class basic_option { public: // construct/copy/destruct basic_option(); basic_option(const std::string &, const std::vector< std::string > &); // public data members std::string string_key; int position_key; std::vector< std::basic_string< charT > > value; std::vector< std::basic_string< charT > > original_tokens; bool unregistered; bool case_insensitive; };
Description
Option found in input source. Contains a key and a value. The key, in turn, can be a string (name of an option), or an integer (position in input source) <ndash></ndash> in case no name is specied. The latter is only possible for command line. The template parameter species the type of char used for storing the option's value.
basic_option public construct/copy/destruct
1.
basic_option();
2.
basic_option(const std::string & xstring_key, const std::vector< std::string > & xvalue);
1.
std::string string_key;
44
Boost.Program_options
Position key of this option. All options without an explicit name are sequentially numbered starting from 0. If an option has explicit name, 'position_key' is equal to -1. It is possible that both position_key and string_key is specied, in case name is implicitly added. 3.
std::vector< std::basic_string< charT > > value;
Option's value 4.
std::vector< std::basic_string< charT > > original_tokens;
True if option was not recognized. In that case, 'string_key' and 'value' are results of purely syntactic parsing of source. The original tokens can be recovered from the "original_tokens" member. 6.
bool case_insensitive;
Header <boost/program_options/options_description.hpp>
namespace boost { namespace program_options { class option_description; class options_description_easy_init; class options_description; class duplicate_option_error; } }
Class option_description
boost::program_options::option_description
45
Boost.Program_options
Synopsis
// In header: <boost/program_options/options_description.hpp>
class option_description { public: enum match_result { no_match, full_match, approximate_match }; // construct/copy/destruct option_description(); option_description(const char *, const value_semantic *); option_description(const char *, const value_semantic *, const char *); ~option_description(); // public member functions match_result match(const std::string &, bool, bool, bool) const; const std::string & key(const std::string &) const; std::string canonical_display_name(int = 0) const; const std::string & long_name() const; const std::string & description() const; shared_ptr< const value_semantic > semantic() const; std::string format_name() const; std::string format_parameter() const; // private member functions option_description & set_name(const char *); };
Description
Describes one possible command line/cong le option. There are two kinds of properties of an option. First describe it syntactically and are used only to validate input. Second affect interpretation of the option, for example default value for it or function that should be called when the value is nally known. Routines which perform parsing never use second kind of properties <ndash></ndash> they are side effect free. See Also: options_description
option_description public construct/copy/destruct
1.
option_description();
2.
Initializes the object with the passed data. Note: it would be nice to make the second parameter auto_ptr, to explicitly pass ownership. Unfortunately, it's often needed to create objects of types derived from 'value_semantic': options_description d; d.add_options()("a", parameter<int>("n")>default_value(1)); Here, the static type returned by 'parameter' should be derived from value_semantic. Alas, derived->base c o nve r s i o n for auto_ptr does not really work, see http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/papers/2000/n1232.pdf http://std.dkuug.dk/jtc1/sc22/wg21/docs/cwg_defects.html#84 So, we have to use plain old pointers. Besides, users are not expected to use the constructor directly.
46
Boost.Program_options
The 'name' parameter is interpreted by the following rules: if there's no "," character in 'name', it species long name otherwise, the part before "," species long name and the part after <ndash></ndash> short name. 3.
option_description(const char * name, const value_semantic * s, const char * description);
1.
match_result match(const std::string & option, bool approx, bool long_ignore_case, bool short_ignore_case) const;
Given 'option', specied in the input source, returns 'true' if 'option' species *this. 2.
const std::string & key(const std::string & option) const;
Returns the key that should identify the option, in particular in the variables_map class. The 'option' parameter is the option spelling from the input source. If option name contains '*', returns 'option'. If long name was specied, it's the long name, otherwise it's a short name with prepended '-'. 3.
std::string canonical_display_name(int canonical_option_style = 0) const;
Returns the canonical name for the option description to enable the user to recognised a matching option. 1) For short options ('', '/'), returns the short name prexed. 2) For long options (' <ndash></ndash> ' / '-') returns the long name prexed 3) All other cases, returns the long name (if present) or the short name, unprexed. 4.
const std::string & long_name() const;
5.
47
Boost.Program_options
Returns the parameter name and properties, formatted suitably for usage message.
option_description private member functions
1.
Class options_description_easy_init
boost::program_options::options_description_easy_init
Synopsis
// In header: <boost/program_options/options_description.hpp>
class options_description_easy_init { public: // construct/copy/destruct options_description_easy_init(options_description *); // public member functions options_description_easy_init & operator()(const char *, const char *); options_description_easy_init & operator()(const char *, const value_semantic *); options_description_easy_init & operator()(const char *, const value_semantic *, const char *); };
Description
Class which provides convenient creation syntax to option_description.
options_description_easy_init public construct/copy/destruct
1.
options_description_easy_init(options_description * owner);
1.
2.
3.
options_description_easy_init & operator()(const char * name, const value_semantic * s, const char * description);
48
Boost.Program_options
Class options_description
boost::program_options::options_description
Synopsis
// In header: <boost/program_options/options_description.hpp>
class options_description { public: // construct/copy/destruct options_description(unsigned = m_default_line_length, unsigned = m_default_line_length/2); options_description(const std::string &, unsigned = m_default_line_length, unsigned = m_default_line_length/2); // public member functions void add(shared_ptr< option_description >); options_description & add(const options_description &); options_description_easy_init add_options(); const option_description & find(const std::string &, bool, bool = false, bool = false) const; const option_description * find_nothrow(const std::string &, bool, bool = false, bool = false) const; const std::vector< shared_ptr< option_description > > & options() const; void print(std::ostream &) const; // friend functions friend BOOST_PROGRAM_OPTIONS_DECL std::ostream & operator<<(std::ostream &, const options_description &); // public data members static const unsigned m_default_line_length; };
Description
A set of option descriptions. This provides convenient interface for adding new option (the add_options) method, and facilities to search for options by name. See here for option adding interface discussion. See Also: option_description
options_description public construct/copy/destruct
1.
49
Boost.Program_options
Creates the instance. The 'caption' parameter gives the name of this 'options_description' instance. Primarily useful for output. The 'description_length' species the number of columns that should be reserved for the description text; if the option text encroaches into this, then the description will start on the next line.
options_description public member functions
1.
Adds new variable description. Throws duplicate_variable_error if either short or long name matches that of already present one. 2.
options_description & add(const options_description & desc);
Adds a group of option description. This has the same effect as adding all option_descriptions in 'desc' individually, except that output operator will show a separate group. Returns *this. 3.
options_description_easy_init add_options();
Returns an object of implementation-dened type suitable for adding options to options_description. The returned object will have overloaded operator() with parameter type matching 'option_description' constructors. Calling the operator will create new option_description instance and add it. 4.
const option_description & find(const std::string & name, bool approx, bool long_ignore_case = false, bool short_ignore_case = false) const;
5.
const option_description * find_nothrow(const std::string & name, bool approx, bool long_ignore_case = false, bool short_ignore_case = false) const;
6.
7.
Outputs 'desc' to the specied stream, calling 'f' to output each option_description element.
options_description friend functions
1.
friend BOOST_PROGRAM_OPTIONS_DECL std::ostream & operator<<(std::ostream & os, const options_description & desc);
Produces a human readable output of 'desc', listing options, their descriptions and allowed parameters. Other options_description instances previously passed to add will be output separately.
Class duplicate_option_error
boost::program_options::duplicate_option_error
50
Boost.Program_options
Synopsis
// In header: <boost/program_options/options_description.hpp>
Description
Class thrown when duplicate option description is found.
duplicate_option_error public construct/copy/destruct
1.
51
Boost.Program_options
Header <boost/program_options/parsers.hpp>
namespace boost { namespace program_options { template<typename charT> class basic_parsed_options; template<> class basic_parsed_options<wchar_t>; template<typename charT> class basic_command_line_parser; enum collect_unrecognized_mode; typedef basic_parsed_options< char > parsed_options; typedef basic_parsed_options< wchar_t > wparsed_options; typedef function1< std::pair< std::string, std::string >, const std::string & > ext_parser; typedef basic_command_line_parser< char > command_line_parser; typedef basic_command_line_parser< wchar_t > wcommand_line_parser; template<typename charT> basic_parsed_options< charT > parse_command_line(int, const charT *const, const options_description &, int = 0, func tion1< std::pair< std::string, std::string >, const std::string & > = ext_parser()); template<typename charT> BOOST_PROGRAM_OPTIONS_DECL basic_parsed_options< charT > parse_config_file(std::basic_istream< charT > &, const options_description &, bool = false); template<typename charT> BOOST_PROGRAM_OPTIONS_DECL basic_parsed_options< charT > parse_config_file(const char *, const options_description &, bool = false); template<typename charT> std::vector< std::basic_string< charT > > collect_unrecognized(const std::vector< basic_option< charT > > &, enum collect_unrecognized_mode); BOOST_PROGRAM_OPTIONS_DECL parsed_options parse_environment(const options_description &, const function1< std::string, std::string > &); BOOST_PROGRAM_OPTIONS_DECL parsed_options parse_environment(const options_description &, const std::string &); BOOST_PROGRAM_OPTIONS_DECL parsed_options parse_environment(const options_description &, const char *); BOOST_PROGRAM_OPTIONS_DECL std::vector< std::string > split_unix(const std::string &, const std::string & = " \t", const std::string & = "'\"", const std::string & = "\\"); BOOST_PROGRAM_OPTIONS_DECL std::vector< std::wstring > split_unix(const std::wstring &, const std::wstring & = L" \t", const std::wstring & = L"'\"", const std::wstring & = L"\\"); } }
52
Boost.Program_options
Synopsis
// In header: <boost/program_options/parsers.hpp> template<typename charT> class basic_parsed_options { public: // construct/copy/destruct explicit basic_parsed_options(const options_description *, int = 0); // public data members std::vector< basic_option< charT > > options; const options_description * description; int m_options_prefix; };
Description
Results of parsing an input source. The primary use of this class is passing information from parsers component to value storage component. This class does not makes much sense itself.
basic_parsed_options public construct/copy/destruct
1.
1.
Options description that was used for parsing. Parsers should return pointer to the instance of option_description passed to them, and issues of lifetime are up to the caller. Can be NULL. 3.
int m_options_prefix;
Mainly used for the diagnostic messages in exceptions. The canonical option prex for the parser which generated these results, depending on the settings for basic_command_line_parser::style() or cmdline::style(). In order of precedence of command_line_style enums: allow_long allow_long_disguise allow_dash_for_short allow_slash_for_short Specializations Class basic_parsed_options<wchar_t>
Class basic_parsed_options<wchar_t>
boost::program_options::basic_parsed_options<wchar_t>
53
Boost.Program_options
Synopsis
// In header: <boost/program_options/parsers.hpp>
class basic_parsed_options<wchar_t> { public: // construct/copy/destruct explicit basic_parsed_options(const basic_parsed_options< char > &); // public data members std::vector< basic_option< wchar_t > > options; const options_description * description; basic_parsed_options< char > utf8_encoded_options; int m_options_prefix; };
Description
Specialization of basic_parsed_options which: provides convenient conversion from basic_parsed_options<char> stores the passed char-based options for later use.
basic_parsed_options public construct/copy/destruct
1.
1.
Stores UTF8 encoded options that were passed to constructor, to avoid reverse conversion in some cases. 2.
int m_options_prefix;
Mainly used for the diagnostic messages in exceptions. The canonical option prex for the parser which generated these results, depending on the settings for basic_command_line_parser::style() or cmdline::style(). In order of precedence of command_line_style enums: allow_long allow_long_disguise allow_dash_for_short allow_slash_for_short
54
Boost.Program_options
Synopsis
// In header: <boost/program_options/parsers.hpp> template<typename charT> class basic_command_line_parser : private cmdline { public: // construct/copy/destruct basic_command_line_parser(const std::vector< std::basic_string< charT > > &); basic_command_line_parser(int, const charT *const); // public member functions basic_command_line_parser & options(const options_description &); basic_command_line_parser & positional(const positional_options_description &); basic_command_line_parser & style(int); basic_command_line_parser & extra_parser(ext_parser); basic_parsed_options< charT > run(); basic_command_line_parser & allow_unregistered(); basic_command_line_parser & extra_style_parser(style_parser); };
Description
Command line parser. The class allows one to specify all the information needed for parsing and to parse the command line. It is primarily needed to emulate named function parameters <ndash></ndash> a regular function with 5 parameters will be hard to use and creating overloads with a smaller nuber of parameters will be confusing. For the most common case, the function parse_command_line is a better alternative. There are two typedefs <ndash></ndash> command_line_parser and wcommand_line_parser, for charT == char and charT == wchar_t cases.
basic_command_line_parser public construct/copy/destruct
1.
Creates a command line parser for the specied arguments list. The 'args' parameter should not include program name. 2.
basic_command_line_parser(int argc, const charT *const argv);
Creates a command line parser for the specied arguments list. The parameters should be the same as passed to 'main'.
basic_command_line_parser public member functions
1.
55
Boost.Program_options
3.
Parses the options and returns the result of parsing. Throws on error. 6.
basic_command_line_parser & allow_unregistered();
Species that unregistered options are allowed and should be passed though. For each command like token that looks like an option but does not contain a recognized name, an instance of basic_option<charT> will be added to result, with 'unrecognized' eld set to 'true'. It's possible to collect all unrecognized options with the 'collect_unrecognized' funciton. 7.
basic_command_line_parser & extra_style_parser(style_parser s);
Type collect_unrecognized_mode
boost::program_options::collect_unrecognized_mode
Synopsis
// In header: <boost/program_options/parsers.hpp>
Description
Controls if the 'collect_unregistered' function should include positional options, or not.
Synopsis
// In header: <boost/program_options/parsers.hpp>
typedef function1< std::pair< std::string, std::string >, const std::string & > ext_parser;
Description
Augments basic_parsed_options<wchar_t> with conversion from 'parsed_options'
56
Boost.Program_options
Synopsis
// In header: <boost/program_options/parsers.hpp>
template<typename charT> basic_parsed_options< charT > parse_command_line(int argc, const charT *const argv, const options_description &, int style = 0, func tion1< std::pair< std::string, std::string >, const std::string & > ext = ext_parser());
Description
Creates instance of 'command_line_parser', passes parameters to it, and returns the result of calling the 'run' method.
Synopsis
// In header: <boost/program_options/parsers.hpp>
template<typename charT> BOOST_PROGRAM_OPTIONS_DECL basic_parsed_options< charT > parse_config_file(std::basic_istream< charT > &, const options_description &, bool allow_unregistered = false);
Description
Parse a cong le. Read from given stream.
Synopsis
// In header: <boost/program_options/parsers.hpp>
template<typename charT> BOOST_PROGRAM_OPTIONS_DECL basic_parsed_options< charT > parse_config_file(const char * filename, const options_description &, bool allow_unregistered = false);
57
Boost.Program_options
Description
Parse a cong le. Read from le with the given name. The character type is passed to the le stream.
Synopsis
// In header: <boost/program_options/parsers.hpp>
template<typename charT> std::vector< std::basic_string< charT > > collect_unrecognized(const std::vector< basic_option< charT > > & options, enum collect_unrecognized_mode mode);
Description
Collects the original tokens for all named options with 'unregistered' ag set. If 'mode' is 'include_positional' also collects all positional options. Returns the vector of origianl tokens for all collected options.
Function parse_environment
boost::program_options::parse_environment
Synopsis
// In header: <boost/program_options/parsers.hpp>
BOOST_PROGRAM_OPTIONS_DECL parsed_options parse_environment(const options_description &, const function1< std::string, std::string > & name_mapper);
Description
Parse environment. For each environment variable, the 'name_mapper' function is called to obtain the option name. If it returns empty string, the variable is ignored. This is done since naming of environment variables is typically different from the naming of command line options.
Function parse_environment
boost::program_options::parse_environment
58
Boost.Program_options
Synopsis
// In header: <boost/program_options/parsers.hpp>
Description
Parse environment. Takes all environment variables which start with 'prex'. The option name is obtained from variable name by removing the prex and converting the remaining string into lower case.
Function parse_environment
boost::program_options::parse_environment
Synopsis
// In header: <boost/program_options/parsers.hpp>
Description
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.This function exists to resolve ambiguity between the two above functions when second argument is of 'char*' type. There's implicit conversion to both function1 and string.
Function split_unix
boost::program_options::split_unix
Synopsis
// In header: <boost/program_options/parsers.hpp>
BOOST_PROGRAM_OPTIONS_DECL std::vector< std::string > split_unix(const std::string & cmdline, const std::string & seperator = " \t", const std::string & quote = "'\"", const std::string & escape = "\\"); BOOST_PROGRAM_OPTIONS_DECL std::vector< std::wstring > split_unix(const std::wstring & cmdline, const std::wstring & seperator = L" \t", const std::wstring & quote = L"'\"", const std::wstring & escape = L"\\");
59
Boost.Program_options
Description
Splits a given string to a collection of single strings which can be passed to command_line_parser. The second parameter is used to specify a collection of possible seperator chars used for splitting. The seperator is defaulted to space " ". Splitting is done in a unix style way, with respect to quotes '"' and escape characters '\'
Header <boost/program_options/positional_options.hpp>
namespace boost { namespace program_options { class positional_options_description; } }
Class positional_options_description
boost::program_options::positional_options_description
Synopsis
// In header: <boost/program_options/positional_options.hpp>
class positional_options_description { public: // construct/copy/destruct positional_options_description(); // public member functions positional_options_description & add(const char *, int); unsigned max_total_count() const; const std::string & name_for_position(unsigned) const; };
Description
Describes positional options. The class allows to guess option names for positional options, which are specied on the command line and are identied by the position. The class uses the information provided by the user to associate a name with every positional option, or tell that no name is known. The primary assumption is that only the relative order of the positional options themselves matters, and that any interleaving ordinary options don't affect interpretation of positional options. The user initializes the class by specifying that rst N positional options should be given the name X1, following M options should be given the name X2 and so on.
positional_options_description public construct/copy/destruct
1.
positional_options_description();
1.
60
Boost.Program_options
Species that up to 'max_count' next positional options should be given the 'name'. The value of '-1' means 'unlimited'. No calls to 'add' can be made after call with 'max_value' equal to '-1'. 2.
unsigned max_total_count() const;
Returns the maximum number of positional options that can be present. Can return (numeric_limits<unsigned>::max)() to indicate unlimited number. 3.
const std::string & name_for_position(unsigned position) const;
Returns the name that should be associated with positional options at 'position'. Precondition: position < max_total_count()
Header <boost/program_options/value_semantic.hpp>
namespace boost { namespace program_options { class value_semantic; template<typename charT> class value_semantic_codecvt_helper; template<> class value_semantic_codecvt_helper<char>; template<> class value_semantic_codecvt_helper<wchar_t>; class untyped_value; class typed_value_base; template<typename T, typename charT = char> class typed_value; template<typename T> typed_value< T > * value(); template<typename T> typed_value< T > * value(T *); template<typename T> typed_value< T, wchar_t > * wvalue(); template<typename T> typed_value< T, wchar_t > * wvalue(T *); BOOST_PROGRAM_OPTIONS_DECL typed_value< bool > * bool_switch(); BOOST_PROGRAM_OPTIONS_DECL typed_value< bool > * bool_switch(bool *); } }
Class value_semantic
boost::program_options::value_semantic
61
Boost.Program_options
Synopsis
// In header: <boost/program_options/value_semantic.hpp>
class value_semantic { public: // construct/copy/destruct ~value_semantic(); // public member functions std::string name() const; unsigned min_tokens() const; unsigned max_tokens() const; bool is_composing() const; bool is_required() const; void parse(boost::any &, const std::vector< std::string > &, bool) const; bool apply_default(boost::any &) const; void notify(const boost::any &) const; };
Description
Class which species how the option's value is to be parsed and converted into C++ types.
value_semantic public construct/copy/destruct
1.
~value_semantic();
1.
Returns the name of the option. The name is only meaningful for automatic help message. 2.
unsigned min_tokens() const;
The minimum number of tokens for this option that should be present on the command line. 3.
unsigned max_tokens() const;
The maximum number of tokens for this option that should be present on the command line. 4.
bool is_composing() const;
Returns true if values from different sources should be composed. Otherwise, value from the rst source is used and values from other sources are discarded. 5.
bool is_required() const;
62
Boost.Program_options
6.
void parse(boost::any & value_store, const std::vector< std::string > & new_tokens, bool utf8) const;
Parses a group of tokens that specify a value of option. Stores the result in 'value_store', using whatever representation is desired. May be be called several times if value of the same option is specied more than once. 7.
bool apply_default(boost::any & value_store) const;
Called to assign default value to 'value_store'. Returns true if default value is assigned, and false if no default value exists. 8.
void notify(const boost::any & value_store) const;
Synopsis
// In header: <boost/program_options/value_semantic.hpp> template<typename charT> class value_semantic_codecvt_helper { };
Description
Helper class which perform necessary character conversions in the 'parse' method and forwards the data further. Specializations Class value_semantic_codecvt_helper<char> Class value_semantic_codecvt_helper<wchar_t>
Class value_semantic_codecvt_helper<char>
boost::program_options::value_semantic_codecvt_helper<char>
63
Boost.Program_options
Synopsis
// In header: <boost/program_options/value_semantic.hpp>
class value_semantic_codecvt_helper<char> : public boost::program_options::value_semantic { public: // private member functions void parse(boost::any &, const std::vector< std::string > &, bool) const; // protected member functions void xparse(boost::any &, const std::vector< std::string > &) const; };
Description
Helper conversion class for values that accept ascii strings as input. Overrides the 'parse' method and denes new 'xparse' method taking std::string. Depending on whether input to parse is ascii or UTF8, will pass it to xparse unmodied, or with UTF8->ascii conversion.
value_semantic_codecvt_helper private member functions
1.
void parse(boost::any & value_store, const std::vector< std::string > & new_tokens, bool utf8) const;
Parses a group of tokens that specify a value of option. Stores the result in 'value_store', using whatever representation is desired. May be be called several times if value of the same option is specied more than once.
value_semantic_codecvt_helper protected member functions
1.
void xparse(boost::any & value_store, const std::vector< std::string > & new_tokens) const;
Class value_semantic_codecvt_helper<wchar_t>
boost::program_options::value_semantic_codecvt_helper<wchar_t>
64
Boost.Program_options
Synopsis
// In header: <boost/program_options/value_semantic.hpp>
class value_semantic_codecvt_helper<wchar_t> : public boost::program_options::value_semantic { public: // private member functions void parse(boost::any &, const std::vector< std::string > &, bool) const; // protected member functions void xparse(boost::any &, const std::vector< std::wstring > &) const; };
Description
Helper conversion class for values that accept ascii strings as input. Overrides the 'parse' method and denes new 'xparse' method taking std::wstring. Depending on whether input to parse is ascii or UTF8, will recode input to Unicode, or pass it unmodied.
value_semantic_codecvt_helper private member functions
1.
void parse(boost::any & value_store, const std::vector< std::string > & new_tokens, bool utf8) const;
Parses a group of tokens that specify a value of option. Stores the result in 'value_store', using whatever representation is desired. May be be called several times if value of the same option is specied more than once.
value_semantic_codecvt_helper protected member functions
1.
void xparse(boost::any & value_store, const std::vector< std::wstring > & new_tokens) const;
Class untyped_value
boost::program_options::untyped_value
65
Boost.Program_options
Synopsis
// In header: <boost/program_options/value_semantic.hpp>
class untyped_value : public boost::program_options::value_semantic_codecvt_helper< char > { public: // construct/copy/destruct untyped_value(bool = false); // public member functions std::string name() const; unsigned min_tokens() const; unsigned max_tokens() const; bool is_composing() const; bool is_required() const; void xparse(boost::any &, const std::vector< std::string > &) const; bool apply_default(boost::any &) const; void notify(const boost::any &) const; };
Description
Class which species a simple handling of a value: the value will have string type and only one token is allowed.
untyped_value public construct/copy/destruct
1.
1.
Returns the name of the option. The name is only meaningful for automatic help message. 2.
unsigned min_tokens() const;
The minimum number of tokens for this option that should be present on the command line. 3.
unsigned max_tokens() const;
The maximum number of tokens for this option that should be present on the command line. 4.
bool is_composing() const;
Returns true if values from different sources should be composed. Otherwise, value from the rst source is used and values from other sources are discarded. 5.
bool is_required() const;
66
Boost.Program_options
6.
void xparse(boost::any & value_store, const std::vector< std::string > & new_tokens) const;
If 'value_store' is already initialized, or new_tokens has more than one elements, throws. Otherwise, assigns the rst string from 'new_tokens' to 'value_store', without any modications. 7.
bool apply_default(boost::any &) const;
Does nothing. 8.
void notify(const boost::any &) const;
Does nothing.
Class typed_value_base
boost::program_options::typed_value_base
Synopsis
// In header: <boost/program_options/value_semantic.hpp>
class typed_value_base { public: // construct/copy/destruct ~typed_value_base(); // public member functions const std::type_info & value_type() const; };
Description
Base class for all option that have a xed type, and are willing to announce this type to the outside world. Any 'value_semantics' for which you want to nd out the type can be dynamic_cast-ed to typed_value_base. If conversion succeeds, the 'type' method can be called.
typed_value_base public construct/copy/destruct
1.
~typed_value_base();
1.
67
Boost.Program_options
Synopsis
// In header: <boost/program_options/value_semantic.hpp> template<typename T, typename charT = char> class typed_value : public boost::program_options::value_semantic_codecvt_helper< charT >, public boost::program_options::typed_value_base { public: // construct/copy/destruct typed_value(T *); // public member functions typed_value * default_value(const T &); typed_value * default_value(const T &, const std::string &); typed_value * implicit_value(const T &); typed_value * value_name(const std::string &); typed_value * implicit_value(const T &, const std::string &); typed_value * notifier(function1< void, const T & >); typed_value * composing(); typed_value * multitoken(); typed_value * zero_tokens(); typed_value * required(); std::string name() const; bool is_composing() const; unsigned min_tokens() const; unsigned max_tokens() const; bool is_required() const; void xparse(boost::any &, const std::vector< std::basic_string< charT > > &) const; bool apply_default(boost::any &) const; void notify(const boost::any &) const; const std::type_info & value_type() const; };
Description
Class which handles value of a specic type.
typed_value public construct/copy/destruct
1.
typed_value(T * store_to);
Ctor. The 'store_to' parameter tells where to store the value when it's known. The parameter can be NULL.
typed_value public member functions
1.
Species default value, which will be used if none is explicitly specied. The type 'T' should provide operator<< for ostream. 2.
typed_value * default_value(const T & v, const std::string & textual);
Species default value, which will be used if none is explicitly specied. Unlike the above overload, the type 'T' need not provide operator<< for ostream, but textual representation of default value must be provided by the user. 3.
typed_value * implicit_value(const T & v);
68
Boost.Program_options
Species an implicit value, which will be used if the option is given, but without an adjacent value. Using this implies that an explicit value is optional, but if given, must be strictly adjacent to the option, i.e.: '-ovalue' or ' <ndash></ndash> option=value'. Giving '-o' or ' <ndash></ndash> option' will cause the implicit value to be applied. 4.
typed_value * value_name(const std::string & name);
Species an implicit value, which will be used if the option is given, but without an adjacent value. Using this implies that an explicit value is optional, but if given, must be strictly adjacent to the option, i.e.: '-ovalue' or ' <ndash></ndash> option=value'. Giving '-o' or ' <ndash></ndash> option' will cause the implicit value to be applied. Unlike the above overload, the type 'T' need not provide operator<< for ostream, but textual representation of default value must be provided by the user. 6.
typed_value * notifier(function1< void, const T & > f);
Species that the value is composing. See the 'is_composing' method for explanation. 8.
typed_value * multitoken();
Species that no tokens may be provided as the value of this option, which means that only presense of the option is signicant. For such option to be useful, either the 'validate' function should be specialized, or the 'implicit_value' method should be also used. In most cases, you can use the 'bool_switch' function instead of using this method. 10.
typed_value * required();
12.
13.
69
Boost.Program_options
14.
15.
16.
void xparse(boost::any & value_store, const std::vector< std::basic_string< charT > > & new_tokens) const;
Creates an instance of the 'validator' class and calls its operator() to perform the actual conversion. 17.
bool apply_default(boost::any & value_store) const;
If default value was specied via previous call to 'default_value', stores that value into 'value_store'. Returns true if default value was stored. 18.
void notify(const boost::any & value_store) const;
If an address of variable to store value was specied when creating *this, stores the value there. Otherwise, does nothing. 19.
const std::type_info & value_type() const;
Function value
boost::program_options::value
Synopsis
// In header: <boost/program_options/value_semantic.hpp>
template<typename T> typed_value< T > * value(); template<typename T> typed_value< T > * value(T * v);
Description
Creates a typed_value<T> instance. This function is the primary method to create value_semantic instance for a specic type, which can later be passed to 'option_description' constructor. The second overload is used when it's additionally desired to store the value of option into program variable.
Function wvalue
boost::program_options::wvalue
70
Boost.Program_options
Synopsis
// In header: <boost/program_options/value_semantic.hpp>
template<typename T> typed_value< T, wchar_t > * wvalue(); template<typename T> typed_value< T, wchar_t > * wvalue(T * v);
Description
Creates a typed_value<T> instance. This function is the primary method to create value_semantic instance for a specic type, which can later be passed to 'option_description' constructor.
Function bool_switch
boost::program_options::bool_switch
Synopsis
// In header: <boost/program_options/value_semantic.hpp>
BOOST_PROGRAM_OPTIONS_DECL typed_value< bool > * bool_switch(); BOOST_PROGRAM_OPTIONS_DECL typed_value< bool > * bool_switch(bool * v);
Description
Works the same way as the 'value<bool>' function, but the created value_semantic won't accept any explicit value. So, if the option is present on the command line, the value will be 'true'.
Header <boost/program_options/variables_map.hpp>
namespace boost { namespace program_options { class variable_value; class abstract_variables_map; class variables_map; BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< char > &, variables_map &, bool = false); BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< wchar_t > &, variables_map &); BOOST_PROGRAM_OPTIONS_DECL void notify(variables_map &); } }
Class variable_value
boost::program_options::variable_value
71
Boost.Program_options
Synopsis
// In header: <boost/program_options/variables_map.hpp>
class variable_value { public: // construct/copy/destruct variable_value(); variable_value(const boost::any &, bool); // public member functions template<typename T> const T & as() const; template<typename T> T & as(); bool empty() const; bool defaulted() const; const boost::any & value() const; boost::any & value(); // friend functions friend BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< char > &, variables_map &, bool); };
Description
Class holding value of option. Contains details about how the value is set and allows to conveniently obtain the value.
variable_value public construct/copy/destruct
1.
variable_value();
2.
1.
If stored value if of type T, returns that value. Otherwise, throws boost::bad_any_cast exception. 2.
template<typename T> T & as();
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. 3.
bool empty() const;
Returns true if the value was not explicitly given, but has default value.
72
Boost.Program_options
5.
1.
friend BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< char > & options, variables_map & m, bool);
Stores in 'm' all options that are dened in 'options'. If 'm' already has a non-defaulted value of an option, that value is not changed, even if 'options' specify some value.
Class abstract_variables_map
boost::program_options::abstract_variables_map
Synopsis
// In header: <boost/program_options/variables_map.hpp>
class abstract_variables_map { public: // construct/copy/destruct abstract_variables_map(); abstract_variables_map(const abstract_variables_map *); ~abstract_variables_map(); // public member functions const variable_value & operator[](const std::string &) const; void next(abstract_variables_map *); // private member functions const variable_value & get(const std::string &) const; };
Description
Implements string->string mapping with convenient value casting facilities.
abstract_variables_map public construct/copy/destruct
1.
abstract_variables_map();
2.
3.
~abstract_variables_map();
73
Boost.Program_options
1.
Obtains the value of variable 'name', from *this and possibly from the chain of variable maps. if there's no value in *this. if there's next variable map, returns value from it otherwise, returns empty value if there's defaulted value if there's next varaible map, which has a non-defauled value, return that otherwise, return value from *this if there's a non-defauled value, returns it. 2.
void next(abstract_variables_map * next);
Sets next variable map, which will be used to nd variables not found in *this.
abstract_variables_map private member functions
1.
Class variables_map
boost::program_options::variables_map
74
Boost.Program_options
Synopsis
// In header: <boost/program_options/variables_map.hpp>
class variables_map : public boost::program_options::abstract_variables_map, public std::map< std::string, variable_value > { public: // construct/copy/destruct variables_map(); variables_map(const abstract_variables_map *); // public member functions const variable_value & operator[](const std::string &) const; void clear(); void notify(); // private member functions const variable_value & get(const std::string &) const; // friend functions friend BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< char > &, variables_map &, bool); };
Description
Concrete variables map which store variables in real map. This class is derived from std::map<std::string, variable_value>, so you can use all map operators to examine its content.
variables_map public construct/copy/destruct
1.
variables_map();
2.
1.
2.
void clear();
3.
void notify();
1.
75
Boost.Program_options
1.
friend BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< char > & options, variables_map & xm, bool utf8);
Stores in 'm' all options that are dened in 'options'. If 'm' already has a non-defaulted value of an option, that value is not changed, even if 'options' specify some value.
Function store
boost::program_options::store
Synopsis
// In header: <boost/program_options/variables_map.hpp>
BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< char > & options, variables_map & m, bool utf8 = false);
Description
Stores in 'm' all options that are dened in 'options'. If 'm' already has a non-defaulted value of an option, that value is not changed, even if 'options' specify some value.
Function store
boost::program_options::store
Synopsis
// In header: <boost/program_options/variables_map.hpp>
BOOST_PROGRAM_OPTIONS_DECL void store(const basic_parsed_options< wchar_t > & options, variables_map & m);
Description
Stores in 'm' all options that are dened in 'options'. If 'm' already has a non-defaulted value of an option, that value is not changed, even if 'options' specify some value. This is wide character variant.
Function notify
boost::program_options::notify
76
Boost.Program_options
Synopsis
// In header: <boost/program_options/variables_map.hpp>
Description
Runs all 'notify' function for options in 'm'.
Header <boost/program_options/version.hpp>
BOOST_PROGRAM_OPTIONS_VERSION
Macro BOOST_PROGRAM_OPTIONS_VERSION
BOOST_PROGRAM_OPTIONS_VERSION
Synopsis
// In header: <boost/program_options/version.hpp> BOOST_PROGRAM_OPTIONS_VERSION
Description
The version of the source interface. The value will be incremented whenever a change is made which might cause compilation errors for existing code.
77