这是一个带有默认参数的函数声明:
void func(int a = 1,int b = 1,...,int x = 1)
当我只想设置参数x并为其余参数使用先前的默认参数时,如何避免调用
func(1,1,...,2)
?例如,像func(paramx = 2, others = default)
这样。这是一个带有默认参数的函数声明:
void func(int a = 1,int b = 1,...,int x = 1)
func(1,1,...,2)
?例如,像func(paramx = 2, others = default)
这样。您不能将此作为自然语言的一部分完成。C ++仅允许您默认任何剩余参数,它不支持调用站点的 命名参数 (与 Pascal 和 VBA 相比)。
另一种选择是提供一系列重载函数。
否则,您可以使用可变模板自行构建一些东西。
Bathsheba已经提到了你不能这样做的原因。
解决问题的一个方法可能是将所有参数打包到struct
或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
func({.x = 2});
:) - Rakete1111
x
指定一个值,您必须提供之前的所有内容。 - WhozCraig