[英]Is there a simple way to call a function with default arguments?
这是一个带有默认参数的函数声明:
void func(int a = 1,int b = 1,...,int x = 1)
当我只想设置x
参数时func(1,1,...,2)
如何避免调用func(1,1,...,2)
,而使用以前的默认参数设置其余参数?
例如,就像func(paramx = 2, others = default)
你不能把它作为自然语言的一部分。 C ++只允许您默认任何剩余的参数,并且它不支持调用站点的命名参数 (参见Pascal和VBA)。
另一种方法是提供一套重载函数。
另外,你可以使用可变参数模板自己设计一些东西。
芭丝谢芭已经提到了你不能这样做的原因。
问题的一个解决方案是将所有参数打包到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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.