简体   繁体   English

我如何专门化静态模板类?

[英]How can I specialize a static templated class?

I'm trying to create a static class to store and retrieve assets such as sound buffers and textures. 我正在尝试创建一个静态类来存储和检索声音缓冲区和纹理等资源。 The way this is implemented is identical for both of these cases, so I created a templated static class and tried to specialize them to store and retrieve objects of the respective types. 对于这两种情况,实现它的方式是相同的,因此我创建了一个模板化的静态类,并尝试将它们专门化以存储和检索相应类型的对象。 Here is my idea: 这是我的想法:

template<typename Asset>
class AssetHandler
{
public:
    static const Asset& retrieve_asset(const std::string& asset_file_path)
    {
    //retrieve the asset from m_assets, or load it in...
    }

private:
    static std::unordered_map<std::string, Asset> m_assets;
};

using ImageHandler = AssetHandler<Image>;
using SoundHandler = AssetHandler<Sound>;

Trying to make calls such as ImageHandler::retrieve_asset("image.png") results in a linker error complaining about undefined references to AssetHandler{Image}::m_assets . 尝试进行诸如ImageHandler::retrieve_asset("image.png")调用会导致链接器错误,抱怨对AssetHandler{Image}::m_assets未定义引用。 I've thought about just using inheritance here, but is that really necessary? 我想过在这里使用继承,但这真的有必要吗? How can I get what I already have to work? 我怎样才能得到我已经拥有的东西?

Add after the class: 课后添加:

template<typename Asset>
std::unordered_map<std::string, Asset> AssetHandler<Asset>::m_assets;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM