C++模板专业化概念
我正在探索 C++ 模板专业化,并且试图理解语法规则:
template <typename T> T foo(T a, char b) {
/* some code */
}
template <> _X foo<_Y>(_Z a, _W b) {
/* some code */
}
以我的简单示例为例,其中 _X、_Y、_Z、_W 作为类型占位符。 在我看来,如果我指定了类型 _Z 和 _W,为什么我需要在 <_Y> 中使用 _Y? _Y 必须与 _Z 或 _W 类型相同吗?
无论实现如何 - 我试图理解本主题中的每个教程,但它从未得到正确解释(或者也许只是我:)) - 如果我已经为某些类型定义了专门的模板,为什么用这些类型调用模板函数还不够?为什么我需要 _Y 类型?
为什么我需要像这样调用专用模板: foo<_Y>(c, d) 为什么 foo(c, d) 还不够?
另外,从我所做的所有测试来看,似乎所有类型: _X、_Y、_Z、_W 必须相同,否则会出现构建错误。 真的是这样吗?
我希望这是有道理的。
I'm exploring C++ Template Specialization, and I'm trying to understand the syntax rules:
template <typename T> T foo(T a, char b) {
/* some code */
}
template <> _X foo<_Y>(_Z a, _W b) {
/* some code */
}
take as an example my simple example with the _X, _Y, _Z, _W as type placeholders.
It seems to me that if I specified the types _Z and _W, why do I need the _Y inside the <_Y>?
and does _Y has to be identical to _Z or _W types?
Regardless of the implementation - I'm trying to understand every tutorial in this topic but it is never explained properly (or maybe it's just me :) ) -
If I already defined a specialized template for certain types, why isn't it enough to call the template function with those types? why do I need to have the _Y type?
why do I need to call the specialized template like this: foo<_Y>(c, d)
and why foo(c, d) is not enough?
Also, from all the testing I have been doing it seems that all types:
_X, _Y, _Z, _W must be identical otherwise I get a build error.
Is that really the case?
I hope it makes sense.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不需要。只要可以像在函数调用中一样推导模板参数,就可以省略显式模板参数列表。
例如,
作为
foo
的显式特化,因为主模板中T
的参数可以从第一个推导为int
专业化中的函数参数,与进行函数调用foo(0, '0')
的方式相同(0
的类型为int< /code> 和类型
'0'
是char
),您也不必显式编写foo(0, '0')
。但是,为了匹配主模板,
_W
必须始终为char
。同样,_X
和_Z
(如果给定_Y
)必须都是相同的类型。You don't need to. As long as the template arguments can be deduced as in a function call, you can leave out an explicit template argument list.
For example
works as explicit specialization of
foo<int>
, because the argument forT
in the primary template can be deduced toint
from the first function parameter in the specialization, the same way it would be if you made a function callfoo(0, '0')
(type of0
isint
and type of'0'
ischar
), where you also don't have to writefoo<int>(0, '0')
explicitly.However, in order to match the primary template
_W
must always bechar
. Similarly_X
and_Z
(and if given_Y
) must all be the same type.