fork(2) download
  1. #include <memory>
  2.  
  3. template<class T>
  4. class Handle : public std::shared_ptr<T> {
  5. public:
  6. using std::shared_ptr<T>::shared_ptr;
  7. template<class ResultType>
  8. inline Handle<ResultType>
  9. cast() const {
  10. // Cast Handle to shared_ptr
  11. auto T_sp = static_cast< std::shared_ptr<T> >(*this);
  12. // Cast the data
  13. auto ResultType_sp = std::static_pointer_cast<ResultType>(T_sp);
  14. // Cast back to Handle
  15. return static_cast< Handle<ResultType> >(ResultType_sp);
  16. }
  17. };
  18.  
  19.  
  20. // Usage
  21. struct Base {};
  22. struct Child : public Base {};
  23.  
  24. int main() {
  25. auto child_ptr = Handle<Child>(new Child());
  26. auto base_ptr = child_ptr.cast<Base>(); // Error with this
  27.  
  28. return 0;
  29. }
Success #stdin #stdout 0s 3224KB
stdin
Standard input is empty
stdout
Standard output is empty