r/cpp • u/nathan_baggs • 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
View all comments
Show parent comment
-8
u/OutlandishnessNo8034 Apr 25 '26
It's not about me not wanting to write it. I used to write metaprogramming code and felt very comfortable with it. So writing it is not a problem. Reading it compared to the rust version is the real problem. Na chuj mi to: = I to: {}? Just to list some of the awkwardness of cpp vs new Gen language. Another problem: You assumed that I find it too difficult to write and that's why I don't like it. Completely misjudged, and prejudiced opinion based on what exactly?
As for cpp being competitive again because of the reflections? That's very naive statement. Until cpp will not deal with memory safety, nothing will save it.