使用显式实例化设置类模板的方法
在提出这个问题并阅读了大量有关模板的内容之后,我想知道以下类模板设置是否有意义。
我有一个名为 ResourceManager
的类模板,它只会加载一些特定资源,例如 ResourceManager
、ResourceManager
// ResourceManager.cpp
template class ResourceManager<sf::Image>;
template class ResourceManager<sf::Music>;
...
// Define methods in ResourceManager, including explicit specializations
简而言之,我试图找到最干净的方法来处理声明和定义模板类及其方法,其中一些可能明确专业化。这是一个特殊情况,我知道只会使用一些显式实例化。
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 . 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。
这是完全合法的。
您可能想隐藏它在 typedef 后面进行模板化的事实(如 std::basic_string 所做的那样),然后在标头中添加注释以不要显式使用模板。
资源管理器.h
资源管理器.cpp
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.
ResourceManager.h
ResourceManager.cpp
如果您需要不同的函数实现,根据类型,我建议使用继承而不是模板。
If you require different implementations of the functions, depending on the type, I'd recommend using inheritance instead of templates.