Guest User

Untitled

a guest
Feb 20th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. struct Component
  5. {
  6.     enum types { a, b };
  7.     // Common data such as id
  8. };
  9.  
  10. struct Component_a : public Component
  11. {
  12.     float f1;
  13.     float f2;
  14.     float f3;
  15.  
  16.     Component_a(float f1, float f2, float f3)
  17.     {
  18.         this->f1 = f1;
  19.         this->f2 = f2;
  20.         this->f3 = f3;
  21.     }
  22.  
  23.     void print()
  24.     {
  25.         std::cout << "f1: " << f1 << ", f2: " << f2 << ", f3: " << f3 << std::endl;
  26.     }
  27. };
  28.  
  29. struct Component_b : public Component
  30. {
  31.     int i;
  32.  
  33.     Component_b(int i)
  34.     {
  35.         this->i = i;
  36.     }
  37.  
  38.     void print()
  39.     {
  40.         std::cout << "i: " << i << std::endl;
  41.     }
  42. };
  43.  
  44. struct ComponentUnion {
  45.     union {
  46.         Component_a a;
  47.         Component_b b;
  48.     };
  49.  
  50.     Component::types type;
  51.  
  52.     ComponentUnion(Component_a a)
  53.     {
  54.         this->a = a;
  55.         this->type = Component::types::a;
  56.     }
  57.  
  58.     ComponentUnion(Component_b b)
  59.     {
  60.         this->b = b;
  61.         this->type = Component::types::b;
  62.     }
  63.  
  64. };
  65.  
  66. int main()
  67. {
  68.     std::vector<ComponentUnion> v;
  69.     v.push_back(ComponentUnion( Component_a(0.1f, 0.2f, 0.3f) ));
  70.     v.push_back(ComponentUnion( Component_b(1) ));
  71.    
  72.     for (ComponentUnion& element : v)
  73.     {
  74.         switch (element.type)
  75.         {
  76.         case Component::types::a:
  77.             // Interpret as type Blueprinta
  78.             element.a.print();
  79.             break;
  80.         case Component::types::b:
  81.             // Interpret as type Blueprintb
  82.             element.b.print();
  83.             break;
  84.         }
  85.     }
  86.  
  87.     system("PAUSE");
  88. }
  89.  
  90. /*
  91. Output:
  92. f1: 0.1, f2: 0.2, f3: 0.3
  93. i: 1
  94. */
Add Comment
Please, Sign In to add comment