在函数调用时C++多组参数及其自己的括号?

C++ multiple sets of parameters with their own parentheses on function call?

本文关键字:自己的 参数 函数调用 C++      更新时间:2023-10-16

我已经用C/C++编码一段时间了,我正在使用 https://github.com/jarro2783/cxxopts 库。该库使用add_options((函数来获取其配置,如下所示:

options.add_options() ("option1", "Description1") ("option2", "Description2");

您可以添加任意数量的选项。

令人惊讶的是,这是有效的C/C++并且有效;我从未见过这样的事情。

他们是怎么做到的?此语法有名称吗?

options.add_options()返回一个对象。

该对象具有函数调用运算符重载,该重载采用两个字符串,很可能看起来像

ObjectType& operator()(std::string const& option, std::string const& value);

这允许您链接函数调用。

这是一个演示概念的简单程序。

#include <iostream>
struct Foo
{
Foo& operator()(int x)
{
std::cout << "Got " << x << std::endl;
return *this;
}
};
struct Bar
{
Foo getFoo() { return Foo(); }
};

int main()
{
Bar b;
b.getFoo()(10)(200)(30);
}

程序输出:

Got 10
Got 200
Got 30

main中的该行等效于:

Foo foo = b.getFoo();
foo(10);
foo(200);
foo(30);

附言

就个人而言,我觉得这种编码风格有点晦涩难懂,最好避免。我宁愿看到:

auto& option = options.add_options();
option.addOption("option1", "Description1");
option.addOption("option2", "Description2");

IMO说,这更清楚理解。