Skip to main content

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:

  • user and password are a named legacy_auth group and must be provided together.
  • json conflicts with markdown.
  • the named legacy_auth group depends on profile.

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 alice fails because password is missing from the legacy_auth group.
  • --json --markdown fails because the two output formats conflict.
  • --user alice --password secret fails because legacy_auth depends on profile.
  • --help shows relation metadata next to --user, --password, --json, --markdown, and --profile.