[英]Way to set up class template with explicit instantiations
After asking this question and reading up a lot on templates, I am wondering whether the following setup for a class template makes sense. 在问了这个问题并阅读了很多模板之后,我想知道以下针对类模板的设置是否有意义。
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 . 我有一个名为
ResourceManager
的类模板,它将仅加载一些特定资源,如ResourceManager<sf::Image>
, ResourceManager<sf::Music>
等。显然,我在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. 这是完全合法的。
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. 您可能希望隐藏它在typedef后面进行模板化的事实(例如std :: basic_string这样做),然后在标头中添加注释以免显式使用模板。
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>;
If you require different implementations of the functions, depending on the type, I'd recommend using inheritance instead of templates. 如果根据类型需要不同的函数实现,建议使用继承而不是模板。
class ResourceManager {
// Virtual and non-virtual functions.
}
class ImageManager : public ResourceManager {
// Implement virtual functions.
}
class MusicManager : public ResourceManager {
// Implement virtual functions.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.