C++ 数字模板
数字模板范例和非类型参数
#ifndef PRO1_ARRAYTP_H
#define PRO1_ARRAYTP_H
#include <iostream>
#include <cstdlib>
using namespace std;
template <class T, int n>
class ArrayTP {
private:
T ar[n];
public:
ArrayTP(){};
explicit ArrayTP(const T & v);
virtual T &operator[](int i);
virtual T operator[](int i) const ;
};
template <class T, int n>
ArrayTP<T, n>::ArrayTP(const T &v) {
for (int i = 0; i < n; i++) {
ar[i] = v;
}
}
template <class T, int n>
T & ArrayTP<T, n>::operator[](int i){
if (i < 0 || i >= n) {
cerr << "Error in array limits: " << i << "is out of range\n";
exit(EXIT_FAILURE);
}
return ar[i];
}
template <class T, int n>
T ArrayTP<T, n>::operator[](int i) const {
if (i < 0 || i >= n) {
cerr << "Error in array limits: " << i << "is out of range\n";
exit(EXIT_FAILURE);
}
return ar[i];
}
#endif //PRO1_ARRAYTP_H
#include "arraytp.h"
数字模板的使用范例
#include <iostream>
#include "module11_class_template/arrry/arraytp.h"
using namespace std;
// 数组模板的使用
void useArrayTemplate(){
ArrayTP<int, 10> sums;
ArrayTP<double , 10> aves;
ArrayTP<ArrayTP<int, 5>, 10> twodee;
int i, j;
for (int i = 0; i < 10; i++) {
sums[i] = 0;
for (int i = 0; i < 5; i++) {
twodee[i][j] = (i + 1)*(j + 1);
sums[i] += twodee[i][j];
}
aves[i] = (double)sums[i] / 10;
}
for (int i = 0; i < 10; i++) {
for (int i = 0; i < 5; i++) {
cout.width(2);
cout << twodee[i][j] << ' ';
}
cout << " :sum = ";
cout.widen(3);
cout << sums[i] << ", average = " << aves[i] << endl;
}
cout << "Done.\n";
}
int main() {
useArrayTemplate();
return 0;
}