在 C++ 中模拟函数的关键字参数
Faking keyword arguments to functions in C++

原始链接: https://nibblestew.blogspot.com/2026/06/faking-keyword-arguments-to-functions.html

虽然 Python 的原生关键字参数增强了代码的可读性,但 C++ 缺乏此特性;由于 C++ 语言演进缓慢且由委员会驱动,官方不太可能实现这一功能。此前,通过复杂的宏或模板来模拟关键字参数的尝试大多未能流行。 然而,现代 C++ 提供了一种简洁的变通方法:使用基于结构体的参数和指定初始化器。通过向函数传递一个结构体,开发者可以使用花括号按名称初始化特定字段,而将其余字段设为默认值。虽然这种方法需要多加一对花括号,且看起来稍显别扭,但它有效地模仿了 Python 直观的关键字参数语法,且无需对语言层面进行改动。

Hacker News最新 | 过往 | 评论 | 提问 | 展示 | 招聘 | 提交登录在 C++ 中伪造函数关键字参数 (nibblestew.blogspot.com)6 分,ibobev 发布于 1 小时前 | 隐藏 | 过往 | 收藏 | 讨论 帮助 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:
相关文章

原文

One of the many nice language features in Python are keyword arguments. They make some types of APIs  concise and readable. Like so:

Unfortunately C does not have keyword arguments and, by extension, neither does C++. Adding them as a language feature would take 15-20 years of effort, most of which would consist of trying to convince people via email that such a feature is important and should be added.

There have been attempts to implement this via macros and template magic (link), but they have not seen widespread usage probably because they are using macros and template magic. However it turns out that with modern language features you can fake keyword arguments fairly convincingly. Like so:

The add_argument method takes a single argument which is a struct. The extra curly braces inside the parentheses boil down to "whatever the underlying argument is, construct it in place with these parameters". The dotted names are designated initializers, so those fields get the specified value whereas other fields get their default values.

And there you go, keyword arguments in C++. You just have to squint a bit and pretend not to see the extra curly braces.

联系我们 contact @ memedata.com