r/cpp • • Apr 25 '26

Using Reflection For Parsing Command Line Arguments

I've been very excited about reflection so I built a small library to pass command line arguments

Basic example:

struct Args
{
    std::string first_name;
    int age;
    bool active;
};

// ./program --first-name John --age 99 --active

const auto args = clap::parse<Args>(argc, argv);

assert(args.first_name == "John");
assert(args.age == 99);
assert(args.active);

More interesting example:

struct Args
{
    [[= clap::Description<"host to connect to">{}]]
    std::string host = "localhost";

    [[=clap::ShortName<'p'>{}]]
    std::uint16_t port;

    [[=clap::Env<"RETRY_COUNT">{}]]
    std::uint32_t retry_count;

    std::optional<std::string> log_file;

    [[=clap::ShortName<'e'>{}]]
    bool encrypted;

    [[=clap::ShortName<'c'>{}]]
    bool compressed;

    [[=clap::ShortName<'h'>{}]]
    bool hashed;
};

// ./program -p 8080 -ec

const auto args = clap::parse<Args>(argc, argv);

assert(args.host == "localhost");
assert(args.port == 8080);
assert(args.retry_count == std::stoul(std::getenv("RETRY_COUNT")));
assert(!args.log_file);
assert(args.encrypted);
assert(args.compressed);
assert(!args.hashed);

The amount of code to handle this is actually quite minimal < 500 lines.

There's a few modern goodies that make this code work:

I guess we don't know what "idiomatic" reflection usage is like yet, I'm interested to come back to this code in a years time and see what mistakes I made!

Link to the code: https://github.com/nathan-baggs/clap

Any feedback, queries, questions are welcome!

128 Upvotes

55 comments sorted by

View all comments

Show parent comment

13

u/Healthy-Act3539 Apr 25 '26

Command Line Argument Parser is not that hard of an acronym to come up with, tbh. I never used Rust (nor heard of their clap) yet I see myself easily coming up with it.

-2

u/OutlandishnessNo8034 Apr 25 '26

So why all those years no one from cpp came up with that and after rust did it now cpp says yeah, it's obvious and we'll do the same... But it will have nothing to do with what you did. And if it happens that sounds like it might be, that's just a coincidence... Yeah, right