模板<>在c ++ [英] template<> in c++
问题描述
模板<>
class A {
//一些类数据
};
我已经看过这种代码多次了。
在上面的代码中使用模板<>
是什么?
我们需要使用它的情况是什么?
;>
告诉编译器模板专用化,特别是完全专业化。通常, A类
应该看起来像这样:
;类T>
class A {
//一般实现
};
模板<>
class A< int> {
// ints
的特殊实现};
现在,每当 A< int>
使用,使用专门的版本。您还可以使用它来专门化函数:
模板< class T&
void foo(T t){
// general
}
template<>
void foo< int>(int i){
// for ints
}
//实际上不需要< int&
//作为特殊化可以从参数类型中推导出
template<>
void foo(int i){
//也有效
}
正常情况下,您不应将功能归类,因为简单的重载通常被视为优先:
void foo(int i){
// better
}
现在,为了使它过度,以下是部分专业化:
模板< class T1,class T2>
B类{
};
template< class T1>
class B< T1,int> {
};
工作方式与完全专业化相同,只是当第二个模板参数是
int
(例如,B
,B
,等)。; template<> class A{ //some class data };
I have seen this kind of code many times. what is the use of
template<>
in the above code? And what are the cases where we need mandate the use of it?解决方案
template<>
tells the compiler that a template specialization follows, specifically a full specialization. Normally,class A
would have to look something like this:template<class T> class A{ // general implementation }; template<> class A<int>{ // special implementation for ints };
Now, whenever
A<int>
is used, the specialized version is used. You can also use it to specialize functions:template<class T> void foo(T t){ // general } template<> void foo<int>(int i){ // for ints } // doesn't actually need the <int> // as the specialization can be deduced from the parameter type template<> void foo(int i){ // also valid }
Normally though, you shouldn't specialize functions, as simple overloads are generally considered superior:
void foo(int i){ // better }
And now, to make it overkill, the following is a partial specialization:
template<class T1, class T2> class B{ }; template<class T1> class B<T1, int>{ };
Works the same way as a full specialization, just that the specialized version is used whenever the second template parameter is an
int
(e.g.,B<bool,int>
,B<YourType,int>
, etc).这篇关于模板<>在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!