std::optional的解释和使用
std::optional是c++ 17版本中新增的一个模板类,可以用于处理错误
将其使用之前,需要明白C++常用的两种处理错误的方式:
1.返回错误码(return -1)
2.抛出异常(try catch,throw…)
在c++17中新增了std::optional,用于替代前两种。因为它如果成功,则打印结果,如果为空,打印报错信息
#include <iostream>
#include <optional>
enum ErrCode
{
ERR1,
SUCCESS
};
ErrCode test(int a,int b,int &out) {
if (b == 0)
{
return ErrCode::ERR1;
}
out = a / b;
return ErrCode::SUCCESS;
}
int test2(int a, int b) {
if (b == 0)
{
throw std::overflow_error("div zero");
}
return a / b;
}
std::optional<int> test3(int a, int b) {
std::optional<int> ret = std::nullopt;
if (b == 0)
{
return ret;
}
ret = a / b;
return ret;
}
int main()
{
std::optional<int> res= test3(10,2);
if (res) {
std::cout << *res<< std::endl;
}
else {
std::cout << "err" << std::endl;
}
}

