Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- template<class T>
- class ptr_wrapper
- {
- T * ptr;
- public:
- ptr_wrapper():ptr(nullptr) {}
- ptr_wrapper(T * ptr):ptr(ptr) {}
- ptr_wrapper(const ptr_wrapper& other):ptr(other.ptr) {}
- const T * get() const { return ptr; }
- T * get() { return ptr; }
- ptr_wrapper& operator=(const ptr_wrapper& other) { ptr = other.ptr; return *this; }
- bool operator==(const ptr_wrapper& other) const { return ptr == other.ptr; }
- bool operator!=(const ptr_wrapper& other) const { return ptr != other.ptr; }
- const T& operator*() const { return *ptr; }
- T& operator*() { return *ptr; }
- const T* operator->() const { return ptr; }
- T* operator->() { return ptr; }
- operator bool() const { return ptr != nullptr; }
- bool operator==(const T* other) const { return ptr == other; }
- bool operator!=(const T* other) const { return ptr != other; }
- };
- template<class T>
- bool operator==(const T* p1, const ptr_wrapper<T>& p2)
- {
- return p2 == p1;
- }
- template<class T>
- bool operator!=(const T* p1, const ptr_wrapper<T>& p2)
- {
- return p2 != p1;
- }
- int main()
- {
- using namespace std;
- std::string * ptr = new std::string("hello");
- ptr_wrapper<std::string> a(ptr);
- const ptr_wrapper<std::string> b(a);
- a = b;
- cout << *ptr << " " << *a << " " << *b << endl;
- cout << ptr->length() << " " << a->length() << " " << b->length() << endl;
- if(ptr) cout << "ok ";
- if(a) cout << "ok ";
- cout << (a == ptr) << " " << (ptr == a) << " ";
- cout << (a != ptr) << " " << (ptr != a) << " ";
- cout << (a == b) << " " << (a != b) << " ";
- delete ptr;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment