之前在《更多元的函式回傳型別:optional 與 outcome》這篇文章中,曾經提過在函式需要回傳計算的結果,但是又可能需要回傳處理的狀態(包含錯誤)的時候,除了可以使用簡單的 C++17 的 std::optional 來處理沒有辦法回傳值的狀況外,下面就是一個簡單的例子:
#include <iostream> #include <optional> std::optional<int> compute_opt(const int input) { if (input == 0 || input > 100) return std::nullopt; return 100 / input; } int main(int argc, char** argv) { auto optRes = compute_opt(101); if (optRes) std::cout << "OK: " << *optRes << std::endl; else std::cout << "Error" << std::endl; }