学习要点:
1 特化就是在写完模版后,再针对template<>里面的参数进行针对性的重写
注意特化的时候 不能设定默认值
注意特化的时候 template<>中只写未特化的参数
类名旁边要写<> 里面写上 特化和未特化的参数
2 部分特化: 不是所有的参数都特化
3 偏特化:
类型不进行具体特化, 类模版接收的参数变成这个类型的变种
部分特化:
#include <iostream>
#include <string>
using namespace std;
#include <typeinfo>
template<typename T=int ,int len =10>
class Stack
{
T a[len];
int cur;
public:
Stack():cur(0){ cout << "Stack<T,int>() " << endl;}
const char * element() const
{
return typeid(T).name();
}
int lenth_size() const
{
return len;
}
void push(const T& d) throw(const char*) //异常声明要在函数声明和函数体中都要有
{
if( full() ) throw "堆栈满";
a[cur++] = d;
}
T pop() throw(const char*)
{
if( empty() ) throw "堆栈空";
return a[--cur];
}
const T& top() const throw(const char*)
{
if( empty() ) throw "堆栈空";
return a[cur-1];
}
bool empty() const
{
return cur==0;
}
bool full() const
{
return cur==len;
}
void clear()
{
cur =0;
}
int size() const
{
return cur;
}
};
template<int len>
class Stack<char ,len>
{
char a[len];
int cur;
public:
Stack():cur(0){ cout << "Stack<char,int>() " << endl;}
const char * element() const
{
return "char";
}
int lenth_size() const
{
return len;
}
void push(const char& d) throw(const char*) //异常声明要在函数声明和函数体中都要有
{
if( full() ) throw "堆栈满";
a[cur++] = d;
}
char pop() throw(const char*)
{
if( empty() ) throw "堆栈空";
return a[--cur];
}
const char & top() const throw(const char*)
{
if( empty() ) throw "堆栈空";
return a[cur-1];
}
bool empty() const
{
return cur==0;
}
bool full() const
{
return cur==len;
}
void clear()
{
cur =0;
}
int size() const
{
return cur;
}
};
int main()
{
Stack<int,20> a;
Stack<char,30> b;
}
完全特化和偏特化
#include <iostream>
#include <typeinfo>
using namespace std;
//可以对非类型的数据对特化
template <int n>
class Fact
{
public:
enum {val=Fact<n-1>::val*n};
};
//特化
template <>
class Fact<0>
{
public:
enum {val=1};
};
//对类型做特化与偏特化
template <typename T>
class Type
{
public:
static string name()
{
return typeid(T).name();
}
};
//特化
template <>
class Type<char>
{
public:
static string name()
{
return "char";
}
};
template<>
class Type<double>
{
public:
static string name()
{
return "double";
}
};
template<>
class Type<int>
{
public:
static string name()
{
return "int";
}
};
//偏特化
template<typename T>
class Type<T *>
{
public:
static string name()
{
return Type<T>::name()+" pointer";
}
};
int main()
{
Fact<5> a;
cout << a.val << endl;
cout << Type<char>::name() << endl;
cout << Type<double>::name() << endl;
cout << Type<int>::name() << endl;
cout << Type<int *>::name() << endl;
}