Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning template map value as reference
    primarykey
    data
    text
    <p>Well, I must say that working with C++ templates + stl made of templates + trying to do fast c++11 code is a pain. Mostly, lots of strange compiler errors... I need a help, code:</p> <pre><code>#include &lt;SFML/Graphics.hpp&gt; #include &lt;memory&gt; #include &lt;map&gt; template &lt;class T&gt; class cResourceManager { public: T&amp; get(const std::string &amp; key); bool add(const std::string &amp; key, const std::shared_ptr&lt;T&gt; &amp; ptr); private: std::map &lt;std::string, std::shared_ptr&lt;T&gt; &gt; resources; }; template &lt;class T&gt; T&amp; cResourceManager&lt;T&gt;::get(const std::string &amp; key) { class std::map&lt;std::string, std::shared_ptr&lt;T&gt;&gt;::const_iterator citr = resources.find(key); if (citr != resources.end()) return resources[key]; } template &lt;class T&gt; bool cResourceManager&lt;T&gt;::add(const std::string &amp; key, const std::shared_ptr&lt;T&gt; &amp; ptr) { if (resources.find(key) == resources.end()) { if(ptr != nullptr) { resources.insert( std::move( std::make_pair(key, ptr) ) ); return true; } } return false; } int main(int argc, char **argv) { cResourceManager&lt;sf::Texture&gt; resmgr; resmgr.add("key", std::make_shared&lt;sf::Texture&gt;() ); resmgr.get("key"); return 0; } </code></pre> <p>On the line resmgr.get("key") i get an error <strong>"main.cpp:19:51: error: invalid initialization of reference of type ‘sf::Texture&amp;’ from expression of type ‘std::map, std::shared_ptr, std::less >, std::allocator, std::shared_ptr > > >::mapped_type {aka std::shared_ptr}’"</strong> I have no idea why and trying to understand errors using templates and STL is extremely hard to me. I have no clue what's wrong.</p> <p>The second thing is a little question. On the line: <strong>resources.insert(std::move(std::make_pair(key, ptr)))</strong> do I need the std::move function to get better performance? Because I want to avoid temporary objects when working with cointainers as much as possible but I don't think that I understand everything so I'm not sure about it.</p> <p>Thanks!</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. 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