Relations
This example shows schema-level relationships between options. Use this pattern
when the rule can be described from occurrence alone and should also appear in
generated help. Relation metadata is rendered inline on affected options, while
named groups get their own Option groups: entry.
Source
Source: examples/relations.cc
examples/relations.cc
#include <iostream>
#include "cli/argument.hh"
#include "cli/parser.hh"
struct Args {
cli::Description description{
"Relation metadata example covering groups, conflicts, and depends_on."};
cli::Help<> help;
cli::StringOption<"user"> user{{.help = "Legacy auth user name"}};
cli::StringOption<"password"> password{{.help = "Legacy auth password"}};
cli::Flag<"json"> json{{.help = "Write JSON output"}};
cli::Flag<"markdown"> markdown{{.help = "Write Markdown output"}};
cli::StringOption<"profile"> profile{{.help = "Deployment profile"}};
static constexpr auto relations = cli::relations(
cli::group({.name = "legacy_auth", .members = {"user", "password"}}),
cli::conflicts("json", "markdown"),
cli::depends_on("legacy_auth", "profile"));
};
auto main(int argc, char* argv[]) -> int {
const auto args = cli::parse_or_exit<Args>(argc, argv);
std::cout << "format: " << (args.json ? "json" : "markdown") << '\n';
if (args.user) {
std::cout << "legacy auth: " << *args.user << '\n';
}
if (args.profile) {
std::cout << "profile: " << *args.profile << '\n';
}
return 0;
}
What This Example Shows
The example defines three static relations:
userandpasswordare a namedlegacy_authgroup and must be provided together.jsonconflicts withmarkdown.- the named
legacy_authgroup depends onprofile.
The parser enforces these rules after normal option parsing and before the program uses the parsed values.
Try It
./build/examples/relations --json
./build/examples/relations --user alice --password secret --profile prod
./build/examples/relations --markdown --profile prod
Failure cases:
--user alicefails becausepasswordis missing from thelegacy_authgroup.--json --markdownfails because the two output formats conflict.--user alice --password secretfails becauselegacy_authdepends onprofile.--helpshows relation metadata next to--user,--password,--json,--markdown, and--profile.