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

7

u/JVApen Clever is an insult, not a compliment. - T. Winters Apr 25 '26

I'm sorry if I insulted you. I wasn't purposely assuming anything about your skills.

Sure, a new language can get a better syntax, that's the cost of C++ being in use for such a long time. If I read another variant posted here in another comment, it looks slightly better as the information isn't passed via template arguments inside the attribute.

I get that you think rust like memory safety guarantees are important. I'm sure it is to some folks and specific kinds of programs. I might be wrong here, though I am still convinced this is a minority. Though I'm open for any information to change my mind on that.

-3

u/OutlandishnessNo8034 Apr 25 '26

That's OK, I appreciate. With regards to the memory safety, basically boils down to the point : is your software reliable or not? If that is something that you don't put value in then that's OK, I m not sure if most people do tbh with the quality of engineers coming out that I see, but if you pride yourself as being engineer then in my opinion quality of your software should be something very important to you.