stout代码分析之七:Result类

  Result类似于Option和Try类的组合,内部有三种状态

enum State {
    SOME,
    NONE,
    ERROR
  };
  • SOME表示Result对象有值
  • NONE表示Result对象值为空
  • ERROR表示异常

  api如下:

  • none, 返回状态为NONE的Result实例
  • some,返回状态为SOME的Result实例
  • error, 返回状态为ERROR的Result实例

  还有isNone, isSome, isError等,在此不细讲。

  如Result对象为SOME状态,可通过get得到值。

  如Result对象为ERROR状态,可通过error获取异常信息。

 

  示例代码如下:

#include "stout/result.hpp"
#include "iostream"

int main()
{
  auto a = Result<int>::none();
  auto b = Result<int>::some(100);
  auto c = Result<int>::error("hello");

  std::cout << (a.isNone() ? "a is none" : "a is not none") << std::endl;
  std::cout << (b.isSome() ? "b is some" : "a is not some") << std::endl;
  std::cout << (c.isError() ? "c is error" : "c is not error") << std::endl;
  std::cout << "c's error: " << c.error() << std::endl;
  std::cout << "b's value: " << b.get() << std::endl;
  return 0;
}

 

posted @ 2016-09-19 23:16  后端技术小屋  阅读(251)  评论(0编辑  收藏  举报