fork download
  1. #include <iostream>
  2. #include <map>
  3.  
  4. class TypeRegistry {
  5. public:
  6. TypeRegistry() {
  7. counter = 0;
  8. }
  9.  
  10. template <typename T>
  11. int getTypeId() {
  12. static int id = -1;
  13.  
  14. if (id < 0) {
  15. id = counter++;
  16. }
  17.  
  18. return id;
  19. }
  20.  
  21. static TypeRegistry & getInstance() {
  22. static TypeRegistry t;
  23.  
  24. return t;
  25. }
  26.  
  27. private:
  28. int counter;
  29. };
  30.  
  31. class Foo {
  32. public:
  33. template <typename T>
  34. T & get() {
  35. std::map<int, void*>::iterator i;
  36. int id;
  37.  
  38. id = TypeRegistry::getInstance().getTypeId<T>();
  39. i = this->values.find(id);
  40.  
  41. if (i != this->values.end())
  42. return *(T*)i->second;
  43.  
  44. T *value = new T();
  45. this->values[id] = value;
  46. return *value;
  47. }
  48.  
  49. size_t size() const {
  50. return this->values.size();
  51. }
  52.  
  53. private:
  54. std::map<int, void*> values;
  55. };
  56.  
  57.  
  58.  
  59. int main()
  60. {
  61. Foo a, b;
  62.  
  63. a.get<int>() = 1;
  64. a.get<float>() = 3.14;
  65. b.get<int>() = 2;
  66. b.get<double>() = 3.14159;
  67. b.get<float>() = 1.23;
  68.  
  69. std::cout << "a<int> = " << a.get<int>() << std::endl;
  70. std::cout << "a<float> = " << a.get<float>() << std::endl;
  71. std::cout << "size of a = " << a.size() << std::endl;
  72. std::cout << "b<int> = " << b.get<int>() << std::endl;
  73. std::cout << "b<double> = " << b.get<double>() << std::endl;
  74. std::cout << "b<float> = " << b.get<float>() << std::endl;
  75. std::cout << "size of b = " << b.size() << std::endl;
  76.  
  77. a.get<int>()++;
  78. a.get<float>() += 3.14;
  79. b.get<int>() -= 2;
  80. b.get<double>() *= 3.14159;
  81. b.get<float>() /= 1.23;
  82.  
  83. std::cout << "a<int> = " << a.get<int>() << std::endl;
  84. std::cout << "a<float> = " << a.get<float>() << std::endl;
  85. std::cout << "size of a = " << a.size() << std::endl;
  86. std::cout << "b<int> = " << b.get<int>() << std::endl;
  87. std::cout << "b<double> = " << b.get<double>() << std::endl;
  88. std::cout << "b<float> = " << b.get<float>() << std::endl;
  89. std::cout << "size of b = " << b.size() << std::endl;
  90.  
  91. return 0;
  92. }
  93.  
  94.  
  95.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
a<int> = 1
a<float> = 3.14
size of a = 2
b<int> = 2
b<double> = 3.14159
b<float> = 1.23
size of b = 3
a<int> = 2
a<float> = 6.28
size of a = 2
b<int> = 0
b<double> = 9.86959
b<float> = 1
size of b = 3