I'm new and I'm learning c++ and a bit of the SFML. To test what my studies I started consulting the "SFML game development" book, from wich I got the ResourceHolder in the code.
The problem is that when I try to implement it the code does compile just fine, but it doesn't execute. After many hours of test and various problems I've arrived to the point where i think (Hope) lays the last error.
The problem should be the initialization of the first class, that doesn't initialize because the ResourceHolder that is contained causes problems.
main.cpp
#include "Game.h"
int main(){
std::cout << "enter main" << std::endl;`
Game game;
std::cout << "after initialization" << std::endl;
}
Game.h
#include "ResourceHolder.h
class Game {
public:
typedef ResourceHolder<sf::Texture, ID> TextureHolder;
Game();
private:
ResourceHolder<sf::Texture, ID> media;
};
Game.cpp
#include "Game.h"
Game::Game()
{
std::cout << "initializing game" << std::endl;
}
ResourceHolder.h
#include <map>
#include <string>
#include <memory>
#include <stdexcept>
#include <cassert>
#include <sfml/Graphics.hpp>
#include <iostream>
enum class ID {
Background,
Player,
MAX_ENUM,
};
template <typename Resource, typename Identifier>
class ResourceHolder {
public:
typedef ResourceHolder<sf::Texture, ID> TextureHolder;
ResourceHolder()
{
TextureHolder texture; //todo <--My guess is here starts the trouble
std::cout << "here" << std::endl;
texture.load(ID::Background, "Media/Image1.png");
texture.load(ID::Player, "Media/Image2.png");
}
void load(Identifier id, const std::string& filename);
Resource& get(Identifier id);
const Resource& get(Identifier id) const;
private:
std::map<ID, std::unique_ptr<sf::Texture>> mResourceMap;
//The IDE flags this as non-used ^^^
};
#include "ResourceHolder.inl"
ResourceHolder.inl
template <typename Resource, typename Identifier>
void ResourceHolder<Resource, Identifier>::load(Identifier id, const std::string& filename)
{
std::unique_ptr<sf::Texture> resource(new Resource());
if (!resource->loadFromFile(filename))
throw std::runtime_error("ResourceHolder::load -Failed to load " + filename);
auto inserted = mResourceMap.insert(std::make_pair(id, std::move(resource)));
assert(inserted.second);
}
template <typename Resource, typename Identifier>
Resource& ResourceHolder<Resource, Identifier>::get(Identifier id)
{
auto found = mResourceMap.find(id);
assert(found != mResourceMap.end());
return *found->second;
}
template <typename Resource, typename Identifier>
const Resource& ResourceHolder<Resource, Identifier>::get(Identifier id) const
{
auto found = mResourceMap.find(id);
assert(found != mResourceMap.end());
return *found->second;
}
Thanks in advance!And pls, tell me if I can improve the question in any way, I am scared this could be too verbose even as tho I stripped all non necessary functions and variables.