如果我想限制类模板可以接受的类型,是否应该使用模板的显式实例化?
我有一个模板类,我只想允许使用某些类型。我相信做到这一点的一种方法是在源文件末尾使用显式实例化——我相信如果开发人员尝试实例化不是显式实例化类型之一的类型,这将导致链接器错误。
然而,当我搜索 SO 时,例如在下面的 2 个链接中,我没有看到任何提及使用显式实例化的内容,所以我质疑是否应该使用显式实例化。
有人可以建议吗?
I have a templated class, and I want to only allow certain types to be used. I believe one way to do this is to use explicit instantiation at the end of the source file -- I believe this will cause linker errors if the developer tried to instantiate a type that is not one of the explicitly instantiated types.
However, when I searched on SO, e.g., in the 2 links below, I did not see any mentioning of using explicit instantiation, so I am questioning if explicit instantiation shoudl be used for this.
Could someone advise?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C++ 在过去十年中不断发展,您所描述的是不再需要的常见 hack。此方法(以及几种替代方法)通过结合使用两种次优实践与较旧的 C++ 标准一起使用:在独立翻译单元中定义实际模板并在该翻译单元中显式实例化模板方法(包括其构造函数) ,并且依赖于这样一个事实,否则模板只能在头文件中有效实现。这通过产生神秘的链接故障有效地实现了该目标。
幸运的是,现代 C++ 中不再需要这种 hack。正如我所提到的,C++ 已经发展到可以使用 C++20 约束以清晰、明确的方式指定类似内容的程度:
您的实际模板可以在头文件中正常定义和实现,并且该约束明确地施加了限制,即您的模板只能使用特定类型进行实例化。
C++ has evolved over the last decade, and what you described was a common hack that is no longer necessary. This (and several alternative approaches) was used with older C++ standards by using a combination of two kinds of sub-optimal practices: defining the actual template in a standalone translation unit and explicitly instantiating the template methods (including its constructor) in that translation unit, and by relying on the fact that, otherwise, templates can only be effectively implemented in a header file. This effectively achieves that goal by producing a cryptic link failure.
Fortunately, that hack is not needed in modern C++ any more. As I mentioned, C++ has evolved to the point where something like that can be specified cleanly, explicitly, and in a crystal clear way using C++20 constraints:
Your actual template can be defined and implemented normally, in a header file, and the constraint clearly imposes a restriction that your template be instantiated only with specific types.