[英]In C++, does it make sense to use a function with std::optional<T> parameter, to denote optional parameters?
我知道可以實現帶有可選參數的函數,如下所示:
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
}
}
問題是,在第一種方法中,我可以調用 function 像這樣someFunction(5)
和 C++ 會意識到我選擇不使用可選參數。 但是在第二種方法中,以同樣的方式調用someFunction(5)
會產生錯誤too few arguments to function call
。
我希望能夠在不包括第二種方法的可選參數的情況下調用 function,這可能/推薦嗎?
要以您在這里想要的方式使用它,我相信您需要指定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)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.