我正在撰寫一組回傳狀態列舉類的函式。每當我們遇到問題并停止BigFunction.
Status BigFunction()
{
Status status;
status = function1();
if (status != Status::SUCCESS)
return status;
status = function2();
if (status != Status::SUCCESS)
return status;
// Do more
return status;
}
有沒有“更整潔”的方法來做到這一點?每次都有if陳述句似乎有點麻煩和雜亂?有沒有辦法得到類似的東西return_if_error function1()?
uj5u.com熱心網友回復:
這就是存在例外的原因。如果您無法控制 and 的行為function1,function2您可以創建一個輔助函式(例如check),它會拋出status != Status::SUCCESS:
void check(Status status) {
if (status != Status::SUCCESS)
throw std::runtime_error("Status was not success");
}
然后使用它代替 if 陳述句并將所有內容包裝在 try catch 中:
try {
check(function1());
check(function2());
} catch (const std::runtime_error &e) {
// error handling
}
uj5u.com熱心網友回復:
在大多數編譯器上(我不知道有任何例外),不拋出例外時開銷為零,但是當拋出例外時,展開堆疊非常慢(我見過源聲稱懲罰是 x40 倍)。
出于這個原因,許多開發人員更喜歡僅在例外情況下使用例外;)(對于幾乎不會發生的事情)。
還有其他方法可以滿足您的要求,只需使用&&操作員并提供可以存盤狀態的工具:
struct StatusKeeper {
bool update(Status newStatus) {
status = newStatus;
return status == Status::SUCCESS;
}
bool operator()(Status newStatus) {
return update(newStatus);
}
Status get() const {
return status;
}
operator Status () const {
return status;
}
private:
Status status = Status::SUCCESS;
};
Status BigFunction()
{
StatusKeeper status;
status(function1())
&& status(function2())
&& status(function3());
// or more verbose, but more readable:
status.update(function1())
&& status.update(function2())
&& status.update(function3());
return status;
}
現在,運算子的第二個引數&&僅在第一個引數被評估為時才被評估true。
也有可能為此目的使用 C 宏,但恕我直言,C 中的宏越少越好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410794.html
標籤:
