Casting between types for shared_ptr
template&lt;typename T&gt; 
std::shared_ptr&lt;T&gt; GetComponent(std::shared_ptr&lt;Entity&gt; entity) {
    return std::shared_ptr&lt;T&gt;((T*)entity-&gt;component_map_.at(T::kTYPE).get());
}



Noooo. This is a misuse of shared_ptr's constructor (trying to create a brand-new shared_ptr to manage an object that is already managed), and will lead to double-free bugs or worse. What you meant was to cast the existing smart pointer to your desired smart pointer type:

template&lt;typename T&gt; 
std::shared_ptr&lt;T&gt; GetComponent(std::shared_ptr&lt;Entity&gt; entity) {
    std::shared_ptr&lt;Component&gt; ptr = component_map_.at(T::kTYPE);
    return std::static_pointer_cast&lt;T&gt;(ptr);
}


This is a moderately obscure corner of smart-pointer-land, and you shouldn't be expected to know it; but now that you see it, I bet you're smacking your forehead in disgust. :)

By the way, I see no reason to provide static const kTYPE = -1 in the base class; doesn't that just counterproductively move the diagnosing of several kinds of typo-bugs from compile-time to run-time?

Also, note that std::map is not a hashmap; it's a tree-map. If you really want a hashmap (or if you don't care), and you're using C++11 or later, you should switch to std::unordered_map.


  What about having the static ID of components and using that to map the components in the entity? Any better solutions?


C++11 has a feature designed specifically for this use-case, although I personally have zero experience with it — it's spelled std::type_index. What you're looking for is a std::unordered_map&lt;std::type_index, std::shared_ptr&lt;Component&gt;&gt;.