fork download
  1. #include <iostream>
  2. #include <typeinfo>
  3. #include <typeindex>
  4. #include <unordered_map>
  5.  
  6.  
  7. struct Base {
  8. virtual ~Base() = default;
  9. };
  10.  
  11. struct E1 : Base {int i;};
  12. struct E2 : Base {};
  13.  
  14. struct Data {
  15. std::size_t id;
  16. std::size_t size;
  17. };
  18.  
  19. struct CCollection
  20. {
  21. template <typename T>
  22. std::size_t toId() {
  23. auto it = info.find(typeid(T));
  24. if (it == info.end()) {
  25. it = info.insert({typeid(T), {count++, sizeof(T)}}).first;
  26. }
  27. return it->second.id;
  28. }
  29.  
  30. std::size_t sizeOf(const Base& base) const {
  31. const auto& data = info.at(typeid(base));
  32. return data.size;
  33. }
  34.  
  35. std::size_t count = 0;
  36. std::unordered_map<std::type_index, Data> info;
  37. };
  38.  
  39. int main()
  40. {
  41. CCollection c;
  42.  
  43. const auto e1Id = c.toId<E1>();
  44. const auto e1Size = c.sizeOf(E1{});
  45.  
  46. std::cout << e1Id << " " << e1Size << std::endl;
  47.  
  48. const auto e2Id = c.toId<E2>();
  49. const auto e2Size = c.sizeOf(E2{});
  50.  
  51. std::cout << e2Id << " " << e2Size << std::endl;
  52.  
  53. }
  54.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
0 8
1 4