fork download
  1. #include <vector>
  2. #include <iostream>
  3.  
  4. struct Parent
  5. {
  6. void use() { std::cout << "Parent\n"; }
  7. };
  8.  
  9. struct Derived : public Parent
  10. {
  11. void use() { std::cout << "Derived\n"; }
  12. };
  13.  
  14. struct Helper
  15. {
  16. Helper(Parent *p) : obj(p) {}
  17. Parent *const obj;
  18. operator Derived *() { return static_cast<Derived *>(obj); }
  19. Derived *operator ->() { return static_cast<Derived *>(obj); }
  20. };
  21.  
  22. template <typename T> struct THelper
  23. {
  24. THelper(Parent *p) : obj(p) {}
  25. Parent *const obj;
  26. operator T *() { return static_cast<T *>(obj); }
  27. T *operator ->() { return static_cast<T *>(obj); }
  28. };
  29.  
  30. int main()
  31. {
  32. std::vector<Parent*> objects { new Derived(), new Derived() };
  33.  
  34. for (Helper h : objects) {
  35. h->use();
  36. }
  37.  
  38. for (THelper<Derived> h : objects) {
  39. Derived *d = h;
  40. d->use();
  41. }
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Derived
Derived
Derived
Derived