CPP-AP 2.2.6
Command-line argument parser for C++20
|
Important:
This tutorial covers the most common use cases and features of the library. For more in-depth information and advanced usage, please refer to the full documentation. Instructions for building the documentation are available in the Dev Notes page.
For CMake projects you can simply fetch the library in your CMakeLists.txt
file:
If you do not use CMake you can dowload the desired library release, extract it in a desired directory and simply add <cpp-ap-dir>/include
to the include directories of your project.
To use the argument parser in your code you need to use the ap::argument_parser
class.
The parameters you can specify for a parser's instance are:
std::cout << parser
).false
by default; if set to true
the parser's configuration output will include more detailed info about arguments' parameters in addition to their names and help messages.
The parser supports both positional and optional arguments. Both argument types are identified by their names represented as strings. Arguments can be defined with only a primary name or with a primary and a secondary (short) name.
Note:
The basic rules of parsing positional and optional arguments are described in the Parsing arguments section.
To add an argument to the parameter's configurations use the following syntax:
or
Note:
The library supports any argument value types which meet the following requirements:
- The
std::ostream& operator<<
is overloaded for the value type- The value type has a copy constructor and an assignment operator
Important:
If the
value_type
is not provided,std::string
will be used.
You can also add boolean flags:
Boolean flags store true
by default but you can specify whether the flag should store true
or false
when used:
Parameters which can be specified for both positional and optional arguments include:
help
- The argument's description which will be printed when printing the parser class instance.choices
- A list of valid argument values.The choices
parameter takes as an argument an instance of std::initializer_list
or any std::ranges::range
type such that its value type is convertible to the argument's value_type
.
Important:
The
choices
function can be used only if the argument'svalue_type
is equality comparable (defines the==
operator).
Actions are represented as functions, which take the argument's value as an argument. The available action types are:
observe
actions | void(const value_type&)
- applied to the parsed value. No value is returned - this action type is used to perform some logic on the parsed value without modifying it.
transform
actions | value_type(const value_type&)
- applied to the parsed value. The returned value will be used to initialize the argument's value.
modify
actions | void(value_type&)
- applied to the initialized value of an argument.
Tip:
A single argument can have multiple value actions. Instead of writing complex logic in one action, consider composing several simple, focused actions for better readability and reuse.
Apart from the common parameters listed above, for optional arguments you can also specify the following parameters:
required
- If this option is set for an argument and it's value is not passed in the command-line, an exception will be thrown.bypass_required
- If this option is set for an argument, parsing it's value will overrite the required
option for other optional arguments and all positional arguments.nargs
- Sets the allowed number of values to be parsed for an argument. This can be set as a:Specific number:
Fully bound range:
Partially bound range:
Unbound range:
Important:
The default
nargs
parameter value isap::nargs::any()
.
default_value
- The default value for an argument which will be used if no values for this argument are parsedimplicit_value
- A value which will be set for an argument if only it's flag is parsed from the command-line but no values follow.In this example if you run the program with only a -s
or --save
flag and no value, the value will be set to out.txt
.
Here the print_debug_info
function will be called right after parsing the --debug-info
flag and the program will exit, even if there are more arguments after this flag.
print_config
| on-flag
Prints the configuration of the parser to the output stream and optionally exits with the given code.
check_file_exists
| observe (value type: std::string
)
Throws if the provided file path does not exist.
gt
| observe (value type: arithmetic)
Validates that the value is strictly greater than lower_bound
.
geq
| observe (value type: arithmetic)
Validates that the value is greater than or equal to lower_bound
.
lt
| observe (value type: arithmetic)
Validates that the value is strictly less than upper_bound
.
leq
| observe (value type: arithmetic)
Validates that the value is less than or equal to upper_bound
.
within
| observe (value type: arithmetic)
Checks if the value is within the given interval. Bound inclusivity is customizable using template parameters.
The CPP-AP
library defines several default arguments, which can be added to the parser's configuration as follows.
Note:
These functions work with
std::initializer_list
and all otherstd::ranges::range
types with the correct value type -ap::argument::default_{positional/optional}
The available default arguments are:
default_positional::input
:
default_positional::output
:
default_optional::help
:
default_optional::input
and default_optional::multi_input
:
default_optional::output
and default_optional::multi_output
:
To parse the command-line arguments use the void argument_parser::parse_args(const AR& argv)
method, where AR
must be a type that satisfies std::ranges::range
and its value type is convertible to std::string
.
The argument_parser
class also defines the void parse_args(int argc, char* argv[])
overload, which works directly with the argc
and argv
arguments of the main
function.
Important:
The
parse_args(argc, argv)
method ignores the first argument (the program name) and is equivalent to calling:parse_args(std::span(argv + 1, argc - 1));
Tip:
The
parse_args
function may throw anap::argument_parser_exception
(specifically theap::parsing_failure
derived exception) if the provided command-line arguments do not match the expected configuration. To simplify error handling, theargument_parser
class providestry_parse_args
methods, which automatically catch these exceptions, print the error message, and exit with a failure status.Internally, This is equivalent to:
try {parser.parse_args(...);}std::cerr << "[ERROR] : " << err.what() << std::endl << parser << std::endl;std::exit(EXIT_FAILURE);}void parse_args(int argc, char *argv[])Parses the command-line arguments.Definition argument_parser.hpp:265Base type for the argument parser functionality errors/exceptions.Definition exceptions.hpp:17
Positional arguments are parsed first, in the order they were defined in and without a flag.
In the example above the first command-line argument must be the value for the positional
argument:
Important:
For each positional argument there must be exactly one value.
Optional arguments are parsed only with a flag:
You can use the flag for each command-line value:
Not using a flag will result in an error:
Important:
The parser behaviour depends on the argument definitions. The argument parameters are described int the Argument parameters section.
You can retrieve the argument's value with:
This will return the value parsed for the given argument.
For optional arguments this will return the argument's predefined value if no value has been parsed. Additionaly, if more than one value has been parsed for an optional argument, this function will return the first parsed value.
value_type{std::forward<U>(default_value)}
(where U
is the deducted type of default_value
), if:
Additionally for optional arguments, you can use:
which returns a vector
containing all values parsed for the given argument.
The library usage examples / demo projects can be found in the cpp-ap-demo repository.