title: Implementing Component system from Unity in c++
body: <p>I've been experimenting with making a component based system similar to Unity's, but in C++. I'm wondering how the <code>GetComponent()</code> method that Unity implements works. It is a very powerful function. Specifically, I want to know what kind of container it uses to store its components.</p>
  <p>The two criteria I need in my clone of this function are as follows. 1. I need any inherited components to be returned as well. For example, if <code>SphereCollider</code> inherits Collider, <code>GetComponent&lt;Collider&gt;()</code> will return the <code>SphereCollider</code> attached to the <code>GameObject</code>, but <code>GetComponent&lt;SphereCollider&gt;()</code> will not return any <code>Collider</code> attached. 2. I need the function to be fast. Preferably, it would use some kind of hash function.</p>
  <p>For criteria one, I know that I could use something similar to the following implementation</p>
  <pre><code>std::vector&lt;Component*&gt; components
  template &lt;typename T&gt;
  T* GetComponent()
  {
      for each (Component* c in components)
          if (dynamic_cast&lt;T&gt;(*c))
              return (T*)c;
      return nullptr;
  }
  </code></pre>
  <p>But that doesn't fit the second criteria of being fast. For that, I know I could do something like this.</p>
  <pre><code>std::unordered_map&lt;type_index, Component*&gt; components
  template &lt;typename T&gt;
  T* GetComponent()
  {
      return (T*)components[typeid(T)];
  }
  </code></pre>
  <p>But again, that doesn't fit the first criteria.</p>
  <p>If anybody knows of some way to combine those two features, even if it's a little slower than the second example, I would be willing to sacrifice a little bit. Thank you!</p>