在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?



我知道可以使用可选参数实现函数,如下所示:

int someFunction(int A, int B = -1) {
if (B != -1) {
... // If B given then do something
} else { 
... // If B not given then do something else
}
}

但是,我会按照同事的建议利用std::optional。这是我正在尝试做的事情,但我收到错误:

int some Function(int A, std::optional<int> B) {
if (B.has_value()) {
... // If B given then do something
} else { 
... // If B not given then do something else
}
}

问题是在第一种方法中,我可以像这样调用函数someFunction(5)并且C++会意识到我选择不使用可选参数。但是在第二个 aproach 中,以相同的方式调用someFunction(5)会产生错误too few arguments to function call

我希望能够在不使用第二种方法中包含可选参数的情况下调用该函数,这可能/推荐吗?

要以您在此处的预期方式使用它,我相信您需要指定默认值std::nullopt

int some Function(int A, std::optional<int> B = std::nullopt) {
if (B.has_value()) {
... // If B given then do something
} else { 
... // If B not given then do something else
}
}

这实际上没有意义; 正常的解决方案是额外的重载int some Function(int A)

相关内容

最新更新