我最近开始使用C ++的模板功能。 不幸的是,我认为我不太明白如何编写模板化类的实现。我有一个带有实现的模板化类,以及一个带有实现的子类的模板化类。编译器在几乎所有类的所有方法上都给出了2019个链接器错误 - 而且我很确定问题在于我实现模板化类的方式。 当我查找这些错误时,大部分时间是在有人忘记实现他在标题中定义的方法时发生的,但我很确定这不是这里的情况。
我的代码如下:
//ResourceManager.h
#ifndef ResMan_H
#define ResMan_H
#include "Loader.h"
#include <iostream>
#include <map>
#include <string>
template<class Res>
class ResourceManager {
private:
std::map<int, Res*> resourceList;
Loader<Res> * loader;
public:
~ResourceManager();
ResourceManager(Loader<Res> * loader);
void load(int key, std::string filePath);
Res* request(int key);
void unload(int key);
void dispose();
};
#endif
实现:
//ResourceManager.cpp
#include "ResourceManager.h"
#include <assert.h>
template<class Res>
ResourceManager<Res>::~ResourceManager(){
this->dispose();
}
ResourceManager<class Res>::ResourceManager(Loader<Res> * loader){
this->loader = loader;
}
void ResourceManager<class Res>::load(int key, std::string filePath){
unload(key);
this->resourceList[key] = this->loader->loadFromFile(filePath);
}
Res* ResourceManager<class Res>::request(int key){
assert(this->resourceList.find(key) == this->resourceList.end() && "Resource could not be found. Make sure to load it before requesting it.");
return this->resourceList[key];
}
template<class Res>
void ResourceManager<Res>::unload(int key){
if (this->resourceList.find(key) != this->resourceList.end()){
delete this->resourceList[key];
this->resourceList.erase(key);
}
}
void ResourceManager<class Res>::dispose(){
for(std::pair<int, Res*> kv : resourceList){
delete kv.second;
}
resourceList.clear();
}
Loader.h
#ifndef Loader_H
#define Loader_H
#include <iostream>
template<class Res>
class Loader {
public:
virtual Res* loadFromFile(std::string filePath);
};
#endif
TextureLoader.h
#ifndef TextureLoader_H
#define TextureLoader_H
#include "Loader.h"
#include <SFML\Graphics.hpp>
class TextureLoader : public Loader<sf::Texture> {
public:
sf::Texture* loadFromFile(std::string path);
};
#endif
实施
#include "TextureLoader.h"
sf::Texture* TextureLoader::loadFromFile(std::string path){
sf::Texture* texture = new sf::Texture();
texture->loadFromFile(path);
std::cout << "Texture loaded" << std::endl;
return texture;
}
对于长代码感到抱歉,但即使这些函数的主体不相关我也宁愿发帖,因为我不是100%错误不在于代码。