Y.L*_*Lex 7 c++ function-parameter default-parameters c++11
这是一个带有默认参数的函数声明:
void func(int a = 1,int b = 1,...,int x = 1)
Run Code Online (Sandbox Code Playgroud)
func(1,1,...,2)
当我只想设置x参数时,如何避免调用,以及使用之前的默认参数设置其余参数?
例如,就像 func(paramx = 2, others = default)
Bat*_*eba 12
你不能把它作为自然语言的一部分.C++只允许您默认任何剩余的参数,并且它不支持调用站点的命名参数(参见Pascal和VBA).
另一种方法是提供一套重载函数.
另外,你可以使用可变参数模板自己设计一些东西.
芭丝谢芭已经提到了你不能这样做的原因.
该问题的一个解决方案是将所有参数打包到a 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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
1 1 1
1 1 2
Run Code Online (Sandbox Code Playgroud)