有没有一种简单的方法来调用带有默认参数的函数?

8

这是一个带有默认参数的函数声明:

void func(int a = 1,int b = 1,...,int x = 1)

当我只想设置参数x并为其余参数使用先前的默认参数时,如何避免调用func(1,1,...,2)?例如,像func(paramx = 2, others = default)这样。

为获取默认参数,您不能在它们之后提供任何内容。因此,如果您想为x指定一个值,您必须提供之前的所有内容 - WhozCraig
2个回答

13

您不能将此作为自然语言的一部分完成。C ++仅允许您默认任何剩余参数,它不支持调用站点的 命名参数 (与 Pascal 和 VBA 相比)。

另一种选择是提供一系列重载函数。

否则,您可以使用可变模板自行构建一些东西。


6

Bathsheba已经提到了你不能这样做的原因。

解决问题的一个方法可能是将所有参数打包到structstd::tuple中(在这里使用struct更直观),只更改你想要的值。(如果允许这样做)

以下是示例代码:

#include <iostream>

struct IntSet
{
    int a = 1; // set default values here
    int b = 1;
    int x = 1;
};

void func(const IntSet& all_in_one)
{
    // code, for instance 
    std::cout << all_in_one.a << " " << all_in_one.b << " " << all_in_one.x << std::endl;
}
int main()
{
    IntSet abx;
    func(abx);  // now you have all default values from the struct initialization

    abx.x = 2;
    func(abx); // now you have x = 2, but all other has default values

    return 0;
}

输出:

1 1 1
1 1 2

2
C++20:func({.x = 2}); :) - Rakete1111

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接