C++模板专业化概念

发布于 2025-01-13 16:47:35 字数 565 浏览 3 评论 0原文

我正在探索 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 技术交流群。

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

发布评论

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

评论(1

战皆罪 2025-01-20 16:47:35

你不需要。只要可以像在函数调用中一样推导模板参数,就可以省略显式模板参数列表。

例如,

template <> int foo(int a, char b) {
   /* some code */
}

作为 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

template <> int foo(int a, char b) {
   /* some code */
}

works as explicit specialization of foo<int>, because the argument for T in the primary template can be deduced to int from the first function parameter in the specialization, the same way it would be if you made a function call foo(0, '0') (type of 0 is int and type of '0' is char), where you also don't have to write foo<int>(0, '0') explicitly.

However, in order to match the primary template _W must always be char. Similarly _X and _Z (and if given _Y) must all be the same type.

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