fork download
  1. #include <iostream>
  2. #include <memory>
  3. #include <map>
  4.  
  5. template <class X>
  6. X& Singleton()
  7. {
  8. static X x;
  9. return x;
  10. }
  11.  
  12. template<class GUID_T, class MAP_T, class T>
  13. class TypeFactory {
  14. protected:
  15. bool ContainsInternal(MAP_T id) {
  16. auto it = types.find(id);
  17. return (it != types.end());
  18. }
  19.  
  20. typedef GUID_T GUID;
  21. inline virtual MAP_T GetTypeID(GUID guid) = 0;
  22. std::map<MAP_T, T> types;
  23. public :
  24. void Add(GUID guid, const T & value) {
  25. auto id = GetTypeID(guid);
  26. if(!ContainsInternal(id)) {
  27. types.insert(std::make_pair(id, T(value)));
  28. }
  29. }
  30.  
  31. bool Contains(GUID guid) {
  32. return ContainsInternal(GetTypeID(guid));
  33. }
  34.  
  35. std::shared_ptr<T> Get(GUID guid) {
  36. auto id = GetTypeID(guid);
  37. std::shared_ptr<T> result;
  38. auto it = types.find(id);
  39. if(it != types.end()) {
  40. result = std::make_shared<T>(it->second);
  41. }
  42. return result;
  43. }
  44.  
  45. std::map<MAP_T, T> & GetAll() {
  46. return types;
  47. }
  48. };
  49.  
  50. template<class T>
  51. class IntTypeFactory : public TypeFactory<int, int, T> {
  52. protected:
  53. inline virtual int GetTypeID(typename TypeFactory<int, int, T>::GUID guid) {
  54. return guid;
  55. }
  56. };
  57. class Type {
  58. public: int a;
  59. };
  60.  
  61. int main() {
  62. IntTypeFactory<Type> & Types (Singleton< IntTypeFactory<Type> >());
  63. IntTypeFactory<Type> & Types2 (Singleton< IntTypeFactory<Type> >());
  64.  
  65. auto t_in = Type();
  66. t_in.a = 10;
  67. Types.Add(1, t_in);
  68. auto t_out = Types2.Get(1);
  69. std::cout << t_out->a << std::endl;
  70. return 0;
  71. }
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
10