如果我想限制类模板可以接受的类型,是否应该使用模板的显式实例化?

发布于 2025-01-11 16:43:35 字数 447 浏览 4 评论 0原文

我有一个模板类,我只想允许使用某些类型。我相信做到这一点的一种方法是在源文件末尾使用显式实例化——我相信如果开发人员尝试实例化不是显式实例化类型之一的类型,这将导致链接器错误。

然而,当我搜索 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?

restrict a template function, to only allow certain types

Restricting templates to only certain classes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘羡 2025-01-18 16:43:35

C++ 在过去十年中不断发展,您所描述的是不再需要的常见 hack。此方法(以及几种替代方法)通过结合使用两种次优实践与较旧的 C++ 标准一起使用:在独立翻译单元中定义实际模板并在该翻译单元中显式实例化模板方法(包括其构造函数) ,并且依赖于这样一个事实,否则模板只能在头文件中有效实现。这通过产生神秘的链接故障有效地实现了该目标。

幸运的是,现代 C++ 中不再需要这种 hack。正如我所提到的,C++ 已经发展到可以使用 C++20 约束以清晰、明确的方式指定类似内容的程度:

#include <type_traits>

template<typename T>
    requires std::is_same_v<T, int> || std::is_same_v<T, char>
struct my_template {};

my_template<int> a;      // OK
my_template<char> b;     // OK
my_template<char *> c;   // ERROR

您的实际模板可以在头文件中正常定义和实现,并且该约束明确地施加了限制,即您的模板只能使用特定类型进行实例化。

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:

#include <type_traits>

template<typename T>
    requires std::is_same_v<T, int> || std::is_same_v<T, char>
struct my_template {};

my_template<int> a;      // OK
my_template<char> b;     // OK
my_template<char *> c;   // ERROR

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文