Outcome.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright 2009-2017 Alibaba Cloud All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. namespace AlibabaCloud
  18. {
  19. namespace OSS
  20. {
  21. template<typename E, typename R>
  22. class Outcome
  23. {
  24. public:
  25. Outcome():success_(false), e_(), r_()
  26. {
  27. }
  28. Outcome(const E& e) :success_(false), e_(e)
  29. {
  30. }
  31. Outcome(const R& r): success_(true), r_(r)
  32. {
  33. }
  34. Outcome(E&& e) : success_(false), e_(std::forward<E>(e))
  35. {
  36. } // Error move constructor
  37. Outcome(R&& r) : success_(true), r_(std::forward<R>(r))
  38. {
  39. } // Result move constructor
  40. Outcome(const Outcome& other) :
  41. success_(other.success_),
  42. e_(other.e_),
  43. r_(other.r_)
  44. {
  45. }
  46. Outcome(Outcome&& other):
  47. success_(other.success_),
  48. e_(std::move(other.e_)),
  49. r_(std::move(other.r_))
  50. {
  51. //*this = std::move(other);
  52. }
  53. Outcome& operator=(const Outcome& other)
  54. {
  55. if (this != &other) {
  56. success_ = other.success_;
  57. e_ = other.e_;
  58. r_ = other.r_;
  59. }
  60. return *this;
  61. }
  62. Outcome& operator=(Outcome&& other)
  63. {
  64. if (this != &other)
  65. {
  66. success_ = other.success_;
  67. r_ = std::move(other.r_);
  68. e_ = std::move(other.e_);
  69. }
  70. return *this;
  71. }
  72. bool isSuccess()const { return success_; }
  73. const E& error()const { return e_; }
  74. const R& result()const { return r_; }
  75. E& error() { return e_; }
  76. R& result() { return r_; }
  77. private:
  78. bool success_;
  79. E e_;
  80. R r_;
  81. };
  82. }
  83. }