onilink_

Pointer Wrapper

Aug 4th, 2015
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. template<class T>
  5. class ptr_wrapper
  6. {
  7.     T * ptr;
  8.    
  9. public:
  10.     ptr_wrapper():ptr(nullptr) {}
  11.     ptr_wrapper(T * ptr):ptr(ptr) {}
  12.     ptr_wrapper(const ptr_wrapper& other):ptr(other.ptr) {}
  13.    
  14.     const T * get() const { return ptr; }
  15.     T * get() { return ptr; }
  16.    
  17.     ptr_wrapper& operator=(const ptr_wrapper& other) { ptr = other.ptr; return *this; }
  18.    
  19.     bool operator==(const ptr_wrapper& other) const { return ptr == other.ptr; }
  20.     bool operator!=(const ptr_wrapper& other) const { return ptr != other.ptr; }
  21.    
  22.     const T& operator*() const { return *ptr; }
  23.     T& operator*() { return *ptr; }
  24.    
  25.     const T* operator->() const { return ptr; }
  26.     T* operator->() { return ptr; }
  27.    
  28.     operator bool() const { return ptr != nullptr; }
  29.    
  30.     bool operator==(const T* other) const { return ptr == other; }
  31.     bool operator!=(const T* other) const { return ptr != other; }
  32. };
  33.  
  34. template<class T>
  35. bool operator==(const T* p1, const ptr_wrapper<T>& p2)
  36. {
  37.     return p2 == p1;
  38. }
  39. template<class T>
  40. bool operator!=(const T* p1, const ptr_wrapper<T>& p2)
  41. {
  42.     return p2 != p1;
  43. }
  44.  
  45. int main()
  46. {
  47.     using namespace std;
  48.    
  49.     std::string * ptr = new std::string("hello");
  50.     ptr_wrapper<std::string> a(ptr);
  51.     const ptr_wrapper<std::string> b(a);
  52.    
  53.     a = b;
  54.    
  55.     cout << *ptr << " " << *a << " " << *b << endl;
  56.     cout << ptr->length() << " " << a->length() << " " << b->length() << endl;
  57.    
  58.     if(ptr) cout << "ok ";
  59.     if(a) cout << "ok ";
  60.     cout << (a == ptr) << " " << (ptr == a) << " ";
  61.     cout << (a != ptr) << " " << (ptr != a) << " ";
  62.     cout << (a == b) << " " << (a != b) << " ";
  63.    
  64.     delete ptr;
  65.    
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment