有没有一种简单的方法可以使用默认参数调用函数?

Is there a simple way to call a function with default arguments?

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

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

如何避免调用func(1,1,...,2) 当我只想设置 x 参数并使用之前的默认参数时?

例如,就像func(paramx = 2, others = default)

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

另一种方法是提供一套重载函数。

否则你可以使用可变参数模板自己设计一些东西。

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

该问题的一个解决方案是将所有参数打包到 struct or std::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