fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <memory>
  4. #include <typeinfo>
  5.  
  6.  
  7. struct Component
  8. {
  9. template<typename T>
  10. T & getAttribute() { return *static_cast<T*>(mAttributes[&typeid(T)].get()); }
  11.  
  12. template<typename T>
  13. void setAttribute(const T & inValue) { mAttributes[&typeid(T)] = std::shared_ptr<void>(new T(inValue)); }
  14.  
  15. std::map<const std::type_info*, std::shared_ptr<void> > mAttributes;
  16. };
  17.  
  18.  
  19. int main()
  20. {
  21. Component comp;
  22. comp.setAttribute<int>(3);
  23. comp.setAttribute<bool>(false);
  24. comp.setAttribute<std::string>("abc");
  25.  
  26. std::cout << comp.getAttribute<int>() << std::endl;
  27. std::cout << comp.getAttribute<bool>() << std::endl;
  28. std::cout << comp.getAttribute<std::string>() << std::endl;
  29.  
  30. }
Success #stdin #stdout 0s 3072KB
stdin
Standard input is empty
stdout
3
0
abc