用显式实例设置类模板的方法 [英] Way to set up class template with explicit instantiations

查看:101
本文介绍了用显式实例设置类模板的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问了这个问题并阅读了很多书之后在模板上,我想知道以下对类模板的设置是否有意义.

After asking this question and reading up a lot on templates, I am wondering whether the following setup for a class template makes sense.

我有一个名为ResourceManager的类模板,该类模板将仅加载一些特定的资源,例如ResourceManager<sf::Image>ResourceManager<sf::Music>等.显然,我在ResourceManager.h中定义了该类模板.但是,由于只有很少的显式实例化,所以做类似...的事情是否合适?

I have a class template called ResourceManager that will only be loading a few specific resources like ResourceManager<sf::Image>, ResourceManager<sf::Music>, etc. Obviously I define the class template in ResourceManager.h . However, since there are only a few explicit instantiations, would it be appropriate to do something like...

// ResourceManager.cpp
template class ResourceManager<sf::Image>;
template class ResourceManager<sf::Music>;
...

// Define methods in ResourceManager, including explicit specializations

简而言之,我正在尝试找到处理声明和定义模板类及其方法的最简洁方法,其中一些可能是显式的专业化知识.这是一种特殊情况,在这种情况下,我知道将只使用一些显式实例化.

In short, I'm trying to find the cleanest way to handle declaring and defining a template class and its methods, some of which may be explicit specializations. This is a special case, in which I know that there will only be a few explicit instantiations used.

推荐答案

是.
这是完全合法的.

Yes.
This is perfectly legittamate.

您可能希望隐藏它在typedef后面进行模板化的事实(例如std :: basic_string这样做),然后在标头中添加注释以免显式使用模板.

You may want to hide the fact that it is templatised behind a typedef (like std::basic_string does) then put a comment in the header not to use the template explicitly.

ResourceManager.h

ResourceManager.h

template<typename T>
class ResourceManager
{
    T& getType();
};

// Do not use ResourceManager<T> directly.
// Use one of the following types explicitly
typedef ResourceManager<sf::Image>   ImageResourceManager;
typedef ResourceManager<sf::Music>   MusicResourceManager;

ResourceManager.cpp

ResourceManager.cpp

#include "ResourceManager.h"

// Code for resource Manager
template<typename T>
T& ResourceManager::getType()
{
    T newValue;
    return newValue;
}

// Make sure only explicit instanciations are valid.
template class ResourceManager<sf::Image>;    
template class ResourceManager<sf::Music>;   

这篇关于用显式实例设置类模板的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆