Bind
Use this when your program already has destination variables and you do not want
to read values back out of Args.
This page is for the case where cli20 is only one part of a larger program and the final state already lives in ordinary local variables or objects.
Source
Source: examples/bind.cc
examples/bind.cc
// bind.cc — demonstrates BoundOption writing directly into application state.
#include <iostream>
#include "cli/argument.hh"
#include "cli/parser.hh"
struct Args {
cli::Description description{
"Bind parsed values into pre-existing variables instead of reading them"
" back from Args."};
cli::Help<> help;
cli::BoundIntOption<"port", 'p'> port;
cli::BoundStringOption<"output", 'o'> output;
cli::BoundDoubleOption<"ratio"> ratio;
};
auto main(int argc, char* argv[]) -> int {
int port = 8080;
std::string output = "out.bin";
double ratio = 1.0;
Args args;
args.port.bind(port);
args.output.bind(output);
args.ratio = ∶
const auto result = cli::Parser<Args>{}.parse(std::move(args), argc, argv);
if (!result) {
std::cerr << result.error.message() << '\n';
return result.error.exit_code();
}
std::cout << "port: " << port << '\n';
std::cout << "output: " << output << '\n';
std::cout << "ratio: " << ratio << '\n';
return 0;
}
What This Example Shows
This example binds parsed values directly into existing variables, so the real
state lives outside Args from the start. It is useful when the surrounding
program already owns port, output, and ratio, and on success those values
are written straight into their target int, std::string, and double
variables.
Try It
cli20@cli20-dev:~$ bind
Things to try:
- Happy path —
--port 9000 --output release.bin --ratio 1.5 - Defaults — run with no arguments to see the pre-bound default values
- Help —
--help - Bad ratio —
--port 80 --ratio abcto see conversion fail