【问题标题】:How can I specialize a static templated class?我怎样才能专门化一个静态模板类?
【发布时间】:2019-03-24 17:22:45
【问题描述】:

我正在尝试创建一个静态类来存储和检索声音缓冲区和纹理等资产。这两种情况的实现方式是相同的,所以我创建了一个模板化的静态类,并尝试将它们专门用于存储和检索各自类型的对象。这是我的想法:

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>;

尝试进行诸如ImageHandler::retrieve_asset("image.png") 之类的调用会导致链接器错误,并抱怨未定义对AssetHandler{Image}::m_assets 的引用。我考虑过在这里只使用继承,但这真的有必要吗?我怎样才能得到我已经必须工作的东西?

【问题讨论】:

    标签: c++ class templates static template-specialization


    【解决方案1】:

    课后添加:

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

    【讨论】:

    • 所以,这行得通,但为什么呢?这里发生了什么?顺便说一句,感谢您的解决方案。
    • 声明与定义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2015-10-30
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多