C++部分模板专门化语法

发布于 2024-10-07 19:18:02 字数 313 浏览 0 评论 0原文

对于主模板:

template<typename A, typename B> class MyClass {...

之间有什么区别

template<typename A, typename B> class MyClass<int, float> {...

对于模板专业化,和

template<> class MyClass<int, float> {...

for primary template:

template<typename A, typename B> class MyClass {...

with template specialization, what is the difference between

template<typename A, typename B> class MyClass<int, float> {...

and

template<> class MyClass<int, float> {...

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

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

发布评论

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

评论(1

嘿看小鸭子会跑 2024-10-14 19:18:02

模板<类型名称 A,类型名称 B>类 MyClass不允许使用 {...。事实上,如果您指定形式参数 AB,您的模板应该使用它们。

第二种情况很正常:你说你正在进行专门化,没有“自由”参数。

中间情况可能

template<typename A> class MyClass<A, float> {...

再次有效:这里您仅修复第二个模板参数。

部分特化的思想如下:创建一个带有一些形式参数的模板,并使用它们来表达对初始模板参数的约束。部分特化的参数不需要与初始模板参数相同。示例:

template<typename X, typename Y, typename Z> class MyClass<X*, Y(Z&)> {...

对于您的案例来说,这是一个有效的部分专业化。这可以理解为“对于任意类型 XYZ,如果 MyClass 的模板参数匹配X*Y(Z&),使用此专业化”。编译器应该非常聪明才能匹配类型模式。

template<typename A, typename B> class MyClass<int, float> {... should be not allowed. Indeed, if you specify the formal parameters A and B, your template should be using them.

The second case is just normal: you say that you are making specialization with no "free" parameters.

An intermediate case could be

template<typename A> class MyClass<A, float> {...

which is again valid: here you are fixing only the 2nd template parameter.

The idea of a partial specialization is following: you make a template with some formal parameters, and use them to express the constraints on the parameters of initial template. The partial specialization's parameters don't need to be the same as the initial template parameters. Example:

template<typename X, typename Y, typename Z> class MyClass<X*, Y(Z&)> {...

would be a valid partial specialization for your case. This can be read as "for arbitrary types X, Y and Z, if MyClass's template parameters match X* and Y(Z&), use this specialization". Compiler should be quite clever in order to match the type pattern.

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