###在函数模板中使用非类型参数
#include<iostream>
using namespace std;
//在函数模板中使用非类型参数
template<class T>void Swap(T &a, T &b);
template<typename T, unsigned N>void Swap(T (&a)[N],T (&b)[N]);
template<typename T, unsigned N>void printArray(T (&arr)[N]);
int main(){
int m = 10, n = 90;
Swap(m,n);
cout << "m = " << m << ", n = " << n << endl;
int a[5] = { 1, 2, 3, 4, 5 };
int b[5] = { 10, 20, 30, 40, 50 };
Swap(a, b);
printArray(a);
printArray(b);
return 0;
}
template<class T> void Swap(T &a,T &b){
T temp = a;
a = b;
b = temp;
}
template<class T, unsigned N> void Swap(T (&a)[N],T (&b)[N]){
T temp;
for (int i = 0; i < N;i++){
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
template<typename T, unsigned N>void printArray(T (&arr)[N]){
for (int i = 0; i < N;i++){
if (i == N-1){
cout << arr[i] << endl;
}
else{
cout << arr[i] << ", ";
}
}
}
#####在类模板中使用非类型参数
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
//动态数组实现,在类模板中使用非类型参数
template<typename T,int N>
class Array{
public:
Array();
~Array();
public:
T & operator[](int i);//重载下标运算符
int length() const{ return m_length; }//获取数组长度
bool capacity(int n);//是否可改变数组容量
private:
int m_length;//数组当前长度
int m_capacity;//当前内存容量
T *m_p;//指向数组内存的指针
};
template<typename T,int N>
Array<T, N>::Array(){
m_p = new T[N];
m_capacity = m_length = N;
}
template<typename T,int N>
Array<T, N>::~Array(){
delete[] m_p;
}
template<typename T,int N>
T & Array<T, N>::operator[](int i){
if (i<0||i>=m_length){
cout << "Exception:Array index out of bounds!" << endl;
}
return m_p[i];
}
template<typename T,int N>
bool Array<T, N>:: capacity(int n){
if (n>0){
int len = m_length + n;
if (len<=m_capacity){
m_length = len;
return true;
}
else{
T *pTemp = new T[m_length + 2 * n*sizeof(T)];
if (NULL==pTemp){
cout << "Exception: Failed to allocate memory!";
return false;
}
else{
memcpy(pTemp,m_p,m_length*sizeof(T));
delete[] m_p;
m_p = pTemp;
m_capacity = m_length = len;
}
}
}
else{
int len = m_length - abs(n);
if (len<0){
cout << "Exception:Array length is too small!" << endl;
return false;
}
else{
m_length = len;
return true;
}
}
}
int main(){
Array<int, 5> arr;
for (int i = 0, len = arr.length(); i < len;i++){
arr[i] = 2 * i;
}
cout << "first print:" << endl;
for (int i = 0, len = arr.length(); i < len;i++){
cout << arr[i] << " ";
}
cout << endl;
//扩大容量为增加的元素赋值
arr.capacity(8);
for (int i = 5, len = arr.length(); i < len;i++){
arr[i] = 2 * i;
}
cout << endl;
cout << "second print:" << endl;
for (int i = 0, len = arr.length(); i < len;i++){
cout << arr[i] << " ";
}
cout << endl;
arr.capacity(-4);
cout << "third print: " << endl;
for (int i = 0, len = arr.length(); i < len; i++){
cout << arr[i] << " ";
}
cout << endl;
return 0;
}