类模板部分特化
下面的代码编译成功,我不明白为什么:
#include <stdio.h>
#include <vector>
#include <iostream>
// Template definition
template <typename T1, typename T2> class stack
{
};
// Template specialization
template <> class stack <float, float>
{
};
int main ()
{
stack <char, char> objStack;
return 0;
}
部分专业化不意味着我们可以将类用于某些特定数据类型,我们在专业?
这里没有 char 的专门类,如果要使用任何类型的数据类型进行编译,那么专门化的目的是什么?
The following code compiles successfully, and I fail to understand why:
#include <stdio.h>
#include <vector>
#include <iostream>
// Template definition
template <typename T1, typename T2> class stack
{
};
// Template specialization
template <> class stack <float, float>
{
};
int main ()
{
stack <char, char> objStack;
return 0;
}
Doesn't Partial Specialization mean that we can use the class for some particular data types, which we specify in the specializations?
There is no specialized class for char here, and if it is going to compile with any kind of data types then what is the purpose of specialization?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模板专业化适用于当您想要对特定模板参数执行一些特别不同的操作时。编译器将实例化原始模板中未指定的任何内容。
当您希望特定数据类型有不同的行为时,这非常有用,但也可用于更复杂的模式匹配,例如更改指针类型或 const 类型的行为:
所以,说来话长简而言之:不必费心指定您的模板,除非您对某个参数有特殊的处理,而您无法将其推广到基本模板中。模板专业化只是模式匹配的一种相当核心的形式,它既可以用于善意,也可以用于邪恶。
Template specialization is for when you want to do something specifically different for specific template parameters. The compiler will instantiate anything non-speficied from the original template.
This is useful for when you want different behavior for a specific data type, but can also be used for more complex pattern matching, such as changing the behavior for pointer types, or
const
types:So, long story short: don't bother specifying your template unless you've got something special to do with a certain parameter, that you can't generalize into the base-template. Template specialization is just a rather hardcore form of pattern-matching which can be used for both good and evil.
模板专业化意味着采用通用模板并添加将用于一组特殊类型的类型或函数。部分特化是指您的模板类型或函数具有多个参数,并且您没有在特化中指定所有参数。
在您的示例中,此函数是通用模板。
它将针对您提供的任何类型进行实例化,除非您提供两个浮点数。如果您提供两个浮点数作为参数,则该模板
将被实例化。
Template specialization means taking a general purpose template and adding a type or function that will be used for a special set of types. Partial specialization is when you have a template type or function with more than one parameter and you do not specify all of the parameters in your specialization.
In your example, this function is the general template.
It will be instantiated for any types you give it EXCEPT for if you give two floats. In the case that you give two floats as parameters this template
will be instantiated.