fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. template <class T>
  5. struct holder {
  6. std::vector<T> data;
  7. };
  8.  
  9. struct gameboy;
  10.  
  11. struct ball { ball(gameboy *) {} };
  12. struct door { door(gameboy *) {} };
  13. struct piss { piss(gameboy *) {} };
  14. struct foo {};
  15.  
  16. struct gameboy
  17. : private holder<ball>
  18. , private holder<door>
  19. , private holder<piss>
  20. {
  21. template <class T>
  22. T & push_back()
  23. {
  24. holder<T> & ancestor = static_cast<holder<T> &>(*this); // compile error here if type mismatch
  25. ancestor.data.push_back(T(this));
  26. return *ancestor.data.rbegin();
  27. }
  28.  
  29. template <class T>
  30. typename std::vector<T>::size_type size() const
  31. {
  32. return holder<T>::data.size(); // or you can just ask your ancestor directly
  33. }
  34. };
  35.  
  36. int main()
  37. {
  38. gameboy boy;
  39. boy.push_back<ball>();
  40. boy.push_back<door>();
  41. boy.push_back<piss>();
  42. boy.push_back<door>();
  43.  
  44. std::cout << boy.size<door>() << std::endl;
  45. // std::cout << boy.size<foo>() << std::endl; // cannot use foo!
  46.  
  47. return 0;
  48. }
Success #stdin #stdout 0.01s 2816KB
stdin
Standard input is empty
stdout
2