compiler error at returning a reference


My error message:
1
2
3
4
5
6
7
8
9
10
11
 test.cpp -lsfml-graphics -lsfml-window -lsfml-system
In file included from test.cpp:1:
./ResourceHolder.hpp:49:12: error: non-const lvalue reference to type
      'sf::Texture' cannot bind to a value of unrelated type 'std::pair<const
      ID::ID, std::unique_ptr<sf::Texture, std::default_delete<sf::Texture> > >'
    return *ptr;
           ^~~~
test.cpp:13:27: note: in instantiation of member function
      'ResourceHolder<ID::ID, sf::Texture>::get' requested here
    sf::Sprite sprite1( r.get(ID::MUSHROOM) );
                          ^


ResourceHolder.hpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#ifndef RESOURCE_HOLDER_HPP
#define RESOURCE_HOLDER_HPP

#include <map>
#include <string>
#include <iostream>
#include <memory>

template <typename Identifier, typename Resource>
class ResourceHolder
{
private:
    std::map<Identifier,std::unique_ptr<Resource>> mResourceList;

public:
    void load( Identifier id, const std::string& filename);
    void remove( Identifier id);
    Resource & get( Identifier id);
};


/*
 * Implementation of template class ResourceHolder
 */
#include <cassert>
#include <utility>

template <typename Identifier, typename Resource>
void ResourceHolder<Identifier,Resource>::load(Identifier id, const std::string & filename)
{
    std::unique_ptr<Resource> resPtr(new Resource);
    assert(resPtr->loadFromFile( filename));
    assert(mResourceList.insert( std::make_pair(id, std::move(resPtr))).second);
}

template <typename Identifier, typename Resource>
void ResourceHolder<Identifier,Resource>::remove(Identifier id)
{
    auto mapPtr = mResourceList.find(id);
    assert(mapPtr != mResourceList.end());
    mResourceList.erase( mapPtr );
}

template <typename Identifier, typename Resource>
Resource & ResourceHolder<Identifier,Resource>::get( Identifier id)
{
    auto ptr = mResourceList.find(id);
    assert (ptr != mResourceList.end());
    return *ptr;
}

#endif // RESOURCE_HOLDER_HPP 


main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "ResourceHolder.hpp"
#include <SFML/Graphics.hpp>

namespace ID { enum ID { ROBOT, MUSHROOM, AIRPLANE }; }

int main()
{
    ResourceHolder<ID::ID, sf::Texture> r;
    r.load(ID::MUSHROOM, "/home/nico/Pictures/sheets/128x128_mushroom.png");

//    r.remove(ID::MUSHROOM);

    sf::Sprite sprite1( r.get(ID::MUSHROOM) );
    sf::Sprite sprite2( r.get(ID::MUSHROOM) );
    ...
}
Try returning *(ptr->second);
Thanks, this works :-)
Topic archived. No new replies allowed.