fork download
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <typeindex>
  4. #include <functional>
  5.  
  6. using namespace std;
  7.  
  8. struct Container {
  9.  
  10. template <class I, class C>
  11. void assoc() {
  12. generators[typeid(I)] = []() -> C * { return new C; };
  13. }
  14.  
  15. template <class I>
  16. I * get() {
  17. auto g = generators[typeid(I)];
  18. return g ? static_cast<I *>(g()) : 0;
  19. }
  20.  
  21. unordered_map<type_index, function<void *(void)>> generators;
  22. };
  23.  
  24. struct IVehicle {
  25. virtual void sayHello() = 0;
  26. };
  27.  
  28. struct Car : IVehicle {
  29. void sayHello() override { cout << "Hello, I am a Car!" << endl; }
  30. };
  31.  
  32. struct Bicycle : IVehicle {
  33. void sayHello() override { cout << "Hello, I am a Bicycle!" << endl; }
  34. };
  35.  
  36. void test(Container & c) {
  37.  
  38. auto v = c.get<IVehicle>();
  39.  
  40. if (v) {
  41. v->sayHello();
  42. } else {
  43. cout << "Couldn't find vehicle :(" << endl;
  44. }
  45.  
  46. }
  47.  
  48. int main() {
  49.  
  50. Container c;
  51.  
  52. test(c);
  53.  
  54. c.assoc<IVehicle, Car>();
  55. test(c);
  56.  
  57. c.assoc<IVehicle, Bicycle>();
  58. test(c);
  59.  
  60. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Couldn't find vehicle :(
Hello, I am a Car!
Hello, I am a Bicycle!