【问题标题】:Passing defaulted/'optional' parameters to C++ functions by name按名称将默认/“可选”参数传递给 C++ 函数
【发布时间】:2021-07-27 15:00:33
【问题描述】:

我是 C++ 新手,正在尝试学习如何在函数中使用可选参数。

现在我知道你可以用这样的可选参数创建一个函数:

void X_plus_Y(int x=10, y=20) {return x + y;}

int main() {

  X_plus_Y(); // returns 30
  X_plus_Y(20); // set x to 20 so return 40
  X_plus_Y(20, 30); // x=20, y=30: return 50
  return 0;
}

但我搜索了互联网并没有找到任何方法来传递这样的可选参数:

X_plus_Y(y=30); // to set only the y to 30 and return 40

有没有办法或“破解”来实现这个结果?

【问题讨论】:

标签: c++ function optional-parameters


【解决方案1】:

命名参数不在该语言中。所以X_plus_Y(y=30); 没有任何意义。您可以获得的最接近的是以下内容:(适用于 clang 11 和 GCC 10.3)

#include <iostream>

struct Args_f
{
        int x = 1;
        int y = 2;
};

int f(Args_f args)
{
        return args.x + args.y;
}

int main()
{
        std::cout << f({ .x = 1}) << '\n'; // prints 3
        std::cout << f({ .y = 2}) << '\n'; // prints 3
        std::cout << f({ .x = 1, .y = 2 }) << std::endl; // prints 3
}

查看https://pdimov.github.io/blog/2020/09/07/named-parameters-in-c20/ 以获得深入的解释。

【讨论】:

  • 正如评论链接所示,我们可以使用最接近的语法。但这种方式更简单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
相关资源
最近更新 更多