Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The fact that the method takes the "key" which appears to be really a type (the type of component to return) indicates to me that the type is not really known until runtime. If that's the case then a compile time mechanism like templates will not do. </p> <p>The only option is to return a base class pointer. And typically when this pattern is used, only virtual methods are called against the base class--so the actual type of the derived class doesn't matter (so no static_cast or dynamic_cast is needed).</p> <p>Edit:</p> <p>As PhilCK noted in comments, the type is actually known at compile time. If that is the case then dynamic type lookup was never really needed, and simple factory methods could have been used:</p> <pre><code>class GameObject { A getComponentA(); B getComponentB(); C getComponentC(); // etc. } // which is more or less identical to: class ComponentFactory { public: virtual Component* create() = 0; }; class GameObject { std::map&lt;std::string,ComponentFactory&gt; m; public: GameObject() { // presumably a private map has to be populated with string -&gt; factory methods here } template&lt;class T&gt; T* getComponent(const std::string&amp; s) { // either the static_cast is needed here, or an alternate (messier) // implementation of getComponent is needed. // it's still possible for the wrong type to be passed (by mistake) // and the compiler won't catch it (with static_cast). Since this could lead // to heap corruption the only safe way with this type of // implementation is dynamic_cast. return static_cast&lt;T&gt;(m[s].create()); } }; // this doesn't even compile: // return types: class GameObject { template &lt;class T&gt; T* getComponent(const std::string&amp; s) { if (s == "A") return new A(); else if (s == "B") return new B(); // etc.. else throw runtime_error("bad type"); } } </code></pre> <p>So there are 2 choices the way I see it.</p> <p>1) use simple factory methods in which case templates are not needed at all. 2) use map -> factory method implementation together with dynamic_cast (which seems to defeat the purpose of using dynamic type creation) and is actually unnecessarily complex if dynamic types aren't needed</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload