0

I am making a game in SFML 2.0 where I have to store different assets like textures, sounds. So I used templates to achieve this.

I have a header file called AssetManager.hpp:

#ifndef ENGINE_ASSETMANAGER_HPP
#define ENGINE_ASSETMANAGER_HPP

#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>

#include <string>
#include <map>

namespace Engine
{
    template <class asset> class AssetManager
    {
        std::map<std::string, asset> data;

        public:
            void add(std::string name, std::string path);

            void remove(std::string name);

            asset &get(std::string name);
    };
}

#endif // ENGINE_ASSETMANAGER_HPP

The type of the template is a class because I'm needing to store class type in a map.

Now the problem is when I try to define the functions in the AssetManager.cpp file:

#include "AssetManager.hpp"

namespace Engine
{
    template <class asset>
    void AssetManager<asset>::add(std::string name, std::string path)
    {
        asset file;
        file.loadFromFile(path);
        this->data[name] = file;
    }

    template <class asset>
    void AssetManager<asset>::remove(std::string name)
    {
        this->data.erase(name);
    }

    template <class asset>
    asset &AssetManager<asset>::get(std::string name)
    {
        return this->data.at(name);
    }
}

I get this one single error that doesn't make sense to me:

error LNK2019: unresolved external symbol "public: void __cdecl Engine::AssetManager<class sf::Texture>::add(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?add@?$AssetManager@VTexture@sf@@@Engine@@QEAAXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@0@Z) referenced in function main
Allen
  • 35
  • 1
  • 4
  • ***Now the problem is when I try to define the functions in the AssetManager.cpp*** Don't do that. Put the template definitions in the `AssetManager.hpp` file and remove the `AssetManager.cpp` file completly. – drescherjm Nov 11 '22 at 22:46
  • Is that really safe to do? Because some people say it bad practice. Either way, if there is at least a workaround for defining the functions in the cpp file, then I would like to know just to keep them organized. – Allen Nov 11 '22 at 23:03
  • ***Is that really safe to do?*** Yes. ***Because some people say it bad practice.*** I think there is some type of miscommunication between what they are saying. Remember that templates are different from non templated code. See the duplicate question for the reason why this is required and a possible work around that is useful in some use cases but only works in some cases. – drescherjm Nov 11 '22 at 23:05
  • 1
    I have moved the definitions in the header now since the work around for this is not what I needed. Thank you for helping! – Allen Nov 12 '22 at 02:06

0 Answers0