Advertisement
mdgaziur001

Option<T> in C++

Apr 9th, 2022
807
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include <exception>
  2. #include <string>
  3.  
  4. class Panic: public std::exception {
  5. public:
  6.     Panic(const char *err): msg(err) {}
  7.     virtual const char* what() const noexcept { return msg.c_str(); }
  8. private:
  9.     std::string msg;
  10. };
  11.  
  12. template<typename T>
  13. class Option {
  14. private:
  15.     T m_Obj;
  16.  
  17.     bool m_Is_Some;
  18.  
  19. public:
  20.     Option(T*, bool);
  21.  
  22.     static Option<T> Some(T);
  23.     static Option<T> None();
  24.  
  25.     T unwrap();
  26.     bool is_some();
  27.     bool is_none();
  28. };
  29.  
  30. template<typename T>
  31. Option<T>::Option(T *object, bool is_some) {
  32.     if (is_some) {
  33.         m_Obj = *object;
  34.     }
  35.     m_Is_Some = is_some;
  36. }
  37.  
  38. template<typename T>
  39. Option<T> Option<T>::Some(T object) {
  40.     return Option(&object, true);
  41. }
  42.  
  43. template<typename T>
  44. Option<T> Option<T>::None() {
  45.     return Option(nullptr, false);
  46. }
  47.  
  48. template<typename T>
  49. T Option<T>::unwrap() {
  50.     if (!m_Is_Some) {
  51.         throw Panic("Option::unwrap() called on 'None' value");
  52.     }
  53.    
  54.     return m_Obj;
  55. }
  56.  
  57. template<typename T>
  58. bool Option<T>::is_some() {
  59.     return m_Is_Some;
  60. }
  61.  
  62. template<typename T>
  63. bool Option<T>::is_none() {
  64.     return !m_Is_Some;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement