Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <variant>
  3. #include <memory>
  4.  
  5. template<typename T>
  6. class value_ptr {
  7. public:
  8.     using element_type = T;
  9.     using pointer = T*;
  10.  
  11.     value_ptr(element_type t) : m_ptr{std::make_unique<T>(std::move(t))} { }
  12.     auto get() const noexcept -> T* { return m_ptr.get(); }
  13.     auto operator*() const -> typename std::add_lvalue_reference<T>::type { return *m_ptr; }
  14.     auto operator->() const noexcept -> T* { return m_ptr.operator->(); }
  15.  
  16. private:
  17.     std::unique_ptr<T> m_ptr;
  18. };
  19.  
  20. template<typename T>
  21. auto operator==(value_ptr<T> const& lhs, value_ptr<T> const& rhs) -> bool { return *lhs == *rhs; }
  22.  
  23. template<typename T>
  24. auto operator!=(value_ptr<T> const& lhs, value_ptr<T> const& rhs) -> bool { return *lhs != *rhs; }
  25.  
  26. template<typename N>
  27. class add;
  28.  
  29. template<typename N>
  30. using expr = std::variant<N, value_ptr<add<N>>>;
  31. //using expr = std::variant<N, std::unique_ptr<add<N>>>; // this works!
  32.  
  33. template<typename N>
  34. class add {
  35. public:
  36.     add(expr<N> lhs, expr<N> rhs) : m_lhs{std::move(lhs)}, m_rhs{std::move(lhs)} {}
  37.     auto lhs() const& -> expr<N> const& { return m_lhs; }
  38.     auto rhs() const& -> expr<N> const& { return m_rhs; }
  39. private:
  40.     expr<N> m_lhs;
  41.     expr<N> m_rhs;
  42. };
  43.  
  44. template<typename N>
  45. auto operator==(add<N> const& lhs, add<N> const& rhs) -> bool {
  46.     return lhs.lhs() == rhs.lhs() && lhs.rhs() == rhs.rhs();
  47. }
  48.  
  49. template<typename N>
  50. auto operator+(expr<N>&& lhs, expr<N>&& rhs) -> expr<N> {
  51.     return value_ptr<add<N>>{add<N>{std::move(lhs), std::move(rhs)}};
  52. //  return std::make_unique<add<N>>(add<N>{std::move(lhs), std::move(rhs)});  // this works!
  53. }
  54.  
  55. auto main() -> int {
  56.     using ex = expr<double>;
  57.     auto x = ex{0.5} + ex{1.5};
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement