fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <memory>
  4.  
  5. using namespace std;
  6.  
  7. struct BaseComponent
  8. {
  9. template <typename T>
  10. T * as()
  11. {
  12. return dynamic_cast<T*>(this);
  13. }
  14.  
  15. virtual ~BaseComponent() {}
  16. };
  17.  
  18. template <typename T>
  19. struct Component : public BaseComponent
  20. {
  21. virtual ~Component() {}
  22. };
  23.  
  24. struct PositionComponent : public Component<PositionComponent>
  25. {
  26. float x, y, z;
  27.  
  28. virtual ~PositionComponent() {}
  29. };
  30.  
  31. struct AnotherComponent : public Component<AnotherComponent>
  32. {
  33. virtual ~AnotherComponent () {}
  34. };
  35.  
  36. int main()
  37. {
  38. std::vector<std::unique_ptr<BaseComponent>> mComponents;
  39. mComponents.emplace_back(new AnotherComponent);
  40.  
  41. auto *pos = mComponents[0]->as<PositionComponent>();
  42. if (pos) {
  43. pos->x = 1337;
  44. } else {
  45. cerr << "Not a PositionComponent." << endl;
  46. }
  47.  
  48. return 0;
  49. }
Success #stdin #stdout #stderr 0s 3468KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Not a PositionComponent.