You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Result.hxx 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //
  2. // Created by robin on 8/9/15.
  3. //
  4. #include "Result.h"
  5. #include <errno.h>
  6. #include <string.h>
  7. template<class T>
  8. Result<T>::Result()
  9. {
  10. }
  11. template<class T>
  12. const Result<T> Result<T>::ok(const T& data)
  13. {
  14. Result<T> r;
  15. r._success = true;
  16. r._data = data;
  17. return r;
  18. }
  19. template<class T>
  20. const Result<T> Result<T>::strerror()
  21. {
  22. Result<T> r;
  23. r._success = false;
  24. r._error = ::strerror(errno);
  25. return r;
  26. }
  27. template<class T>
  28. const Result<T> Result<T>::error(const std::string& error)
  29. {
  30. Result<T> r;
  31. r._success = false;
  32. r._error = error;
  33. return r;
  34. }
  35. template<class T>
  36. template<class U>
  37. const Result<T> Result<T>::error(const Result<U>& other)
  38. {
  39. Result<T> r;
  40. r._success = false;
  41. r.error(other.getError());
  42. return r;
  43. }
  44. template<class T>
  45. T &Result<T>::getData()
  46. {
  47. return _data;
  48. }
  49. template<class T>
  50. const bool Result<T>::isSuccess() const
  51. {
  52. return _success;
  53. }
  54. template<class T>
  55. bool Result<T>::operator!() const
  56. {
  57. return !isSuccess();
  58. }
  59. template<class T>
  60. Result<T>::operator bool() const
  61. {
  62. return isSuccess();
  63. }
  64. template<class T>
  65. const std::string &Result<T>::getError() const
  66. {
  67. return _error;
  68. }
  69. template<class U>
  70. std::ostream& operator<<(std::ostream& os, const Result<U>& res)
  71. {
  72. if (res._success) {
  73. os << "Success";// << res._data;
  74. }
  75. else {
  76. os << "Error: " << (res._error.empty() ? "Unknown error" : res._error);
  77. }
  78. return os;
  79. }
  80. template<class T>
  81. const Result<T>& Result<T>::print() const
  82. {
  83. (_success ? std::cout : std::cerr) << *this << std::endl;
  84. return *this;
  85. }