fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. template<typename T>
  5. struct Key
  6. {
  7. friend T;
  8. };
  9.  
  10. class Service;
  11.  
  12. class Session
  13. {
  14. private:
  15. Session(Service const&) {}
  16.  
  17. public:
  18. void run() { std::cout << "Running!\n"; }
  19.  
  20. // has access to private members of enclosing Session (C++11)
  21. class Guard;
  22. };
  23.  
  24. class Session::Guard
  25. {
  26. public:
  27. Guard(Service const& s, Key<Service>): enclosing(s) {}
  28. Session* operator->() { return &enclosing; }
  29.  
  30. private:
  31. Session enclosing;
  32. };
  33.  
  34. class Service
  35. {
  36. public:
  37. std::shared_ptr<Session::Guard> CreateSession()
  38. {
  39. return std::make_shared<Session::Guard>(*this, Key<Service>{});
  40. }
  41. };
  42.  
  43. int main()
  44. {
  45. Service s;
  46. auto ss = s.CreateSession();
  47. (*ss)->run();
  48. }
Success #stdin #stdout 0s 3028KB
stdin
Standard input is empty
stdout
Running!