簡體   English   中英

在 C++ 中,使用帶有 std::optional 的 function 是否有意義<t>參數,表示可選參數?</t>

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM