在函数调用时C++多组参数及其自己的括号?
C++ multiple sets of parameters with their own parentheses on function call?
我已经用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说,这更清楚理解。
相关文章:
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何访问模板参数自己的模板参数?
- 在类自己的成员函数中构造类时,如何强制类模板参数推导?
- 如何使用自己的参数扩展 PointNormal 类?
- 在函数调用时C++多组参数及其自己的括号?
- 当超出列时,clang格式强制每个参数/参数拥有自己的行?
- GCC 或 Clang 关于函数参数在其自己的默认参数中的范围内的名称是否正确?
- C 超载相等运算符.我应该写自己的功能以接受通过参考或值传递的参数
- LIBSVM SVM 在如何使用我自己(不带"svmpredict")与从"svmtrain"返回的参数
- count_if使用我自己的类实现第三个参数
- 我想根据自己的参数使用count_if
- 知道自己的模板参数模板的模板
- C 是否允许函数以不足的参数来调用自己
- 朋友拥有自己的类模板和其他模板参数
- 如果函数类型仅依赖于其自己的模板参数,则取决于函数类型
- C++ 集<>类对象。使用自己的比较器给出错误:C2804:二进制'operator <'参数过多
- 用C++中的参数在构造函数中定义自己类的数组
- 在自己的默认值中使用参数的名称 - 合法吗?
- 我发现自己无法理解MPI_Gatherv的参数"recvcounts"
- 类对象作为参数传递,访问它们自己的私有成员