假设我有:
void f(bool option1 = false, bool option2 =false, bool option3 = false)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我想打电话给:
f(option2=true);
Run Code Online (Sandbox Code Playgroud)
这在C++中是否可行?
Vit*_*meo 14
无法以您在C++中建议的方式调用函数.您可以通过元编程模拟命名参数,或者只是将a传递struct给您的函数.例如
struct options
{
bool option0{false};
bool option1{false};
bool option2{false};
};
void f(options opts = {});
Run Code Online (Sandbox Code Playgroud)
C++ 11用法:
options opts;
opts.option2 = true;
f(opts);
Run Code Online (Sandbox Code Playgroud)
C++ 2a用法:
f({.option2=true});
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用位标志:
enum FOption
{
option0 = 1 << 0,
option1 = 1 << 1,
option2 = 1 << 2,
};
void f(FOption opt = 0) {
const bool opt0 = opt & option0;
const bool opt1 = opt & option1;
const bool opt2 = opt & option2;
/*...*/
}
Run Code Online (Sandbox Code Playgroud)
然后使用它像:
f(option2);
f(option1 | option2);
Run Code Online (Sandbox Code Playgroud)