daily pastebin goal
32%
SHARE
TWEET

Untitled

a guest Jul 20th, 2018 60 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <memory>
  2. #include <iostream>
  3.  
  4. using std::make_shared;
  5. using std::dynamic_pointer_cast;
  6. using std::cout;
  7. using std::endl;
  8.  
  9.  
  10. class object : public std::enable_shared_from_this<object> {
  11.     private:
  12.         object(const object&) = delete;
  13.         object(const object&&) = delete;
  14.         object& operator=(const object&) = delete;
  15.  
  16.     public:
  17.         object() = default;
  18.     virtual ~object() {}
  19. };
  20.  
  21. /* these should only be enabled for types derived from object */
  22.  
  23. template<class T,
  24.          class = typename std::enable_if<std::is_base_of<object, T>::value>::type>
  25. std::shared_ptr<T> strong_ref_of(T *o) {
  26.     return dynamic_pointer_cast<T>(o->shared_from_this());
  27. }
  28.  
  29. template<class T,
  30.          class = typename std::enable_if<std::is_base_of<object, T>::value>::type>
  31. std::weak_ptr<T> weak_ref_of(T *o) {
  32.     return strong_ref_of(o);
  33. }
  34.  
  35. class branch : public object {
  36.     public:
  37.         void totally() { cout << "totally" << endl; }
  38. };
  39.  
  40. class leaf : public branch {
  41.     public:
  42.         void blah() { cout << "blah" << endl; }
  43. };
  44.  
  45. class leaf_leaf : public leaf {
  46.     public:
  47.         void ohyeah() { cout << "ohyeah" << endl; }
  48. };
  49.  
  50. class broken {
  51.  
  52. };
  53.  
  54. void run() {
  55.     auto thing = make_shared<leaf>();
  56.     auto downcast = dynamic_pointer_cast<object>(thing);
  57.     auto upcast = dynamic_pointer_cast<leaf>(downcast);
  58.     auto branch_cast = dynamic_pointer_cast<branch>(upcast);
  59.     branch* branch_p = branch_cast.get();
  60.     std::shared_ptr<branch> should_work = strong_ref_of(branch_p);
  61.     auto ok = make_shared<leaf_leaf>();
  62.  
  63. #if 0 // strong_ref_of() here fails to compile
  64.     auto b = make_shared<broken>();
  65.     auto ref = strong_ref_of(b);
  66. #endif
  67.  
  68.     ok->ohyeah();
  69.  
  70.     upcast->blah();
  71.     should_work->totally();
  72.  
  73.     cout << thing.use_count() << endl;
  74.     cout << downcast.use_count() << endl;
  75.     cout << upcast.use_count() << endl;
  76.     cout << branch_cast.use_count() << endl;
  77.     cout << should_work.use_count() << endl;
  78.     cout << endl;
  79. }
  80.  
  81. int main(int argc, char ** argv) {
  82.     run();
  83.     return 0;
  84. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top