C++ 数字模板

数字模板范例和非类型参数

arraytp.h

  1. #ifndef PRO1_ARRAYTP_H
  2. #define PRO1_ARRAYTP_H
  3. #include <iostream>
  4. #include <cstdlib>
  5. using namespace std;
  6. template <class T, int n>
  7. class ArrayTP {
  8. private:
  9. T ar[n];
  10. public:
  11. ArrayTP(){};
  12. explicit ArrayTP(const T & v);
  13. virtual T &operator[](int i);
  14. virtual T operator[](int i) const ;
  15. };
  16. template <class T, int n>
  17. ArrayTP<T, n>::ArrayTP(const T &v) {
  18. for (int i = 0; i < n; i++) {
  19. ar[i] = v;
  20. }
  21. }
  22. template <class T, int n>
  23. T & ArrayTP<T, n>::operator[](int i){
  24. if (i < 0 || i >= n) {
  25. cerr << "Error in array limits: " << i << "is out of range\n";
  26. exit(EXIT_FAILURE);
  27. }
  28. return ar[i];
  29. }
  30. template <class T, int n>
  31. T ArrayTP<T, n>::operator[](int i) const {
  32. if (i < 0 || i >= n) {
  33. cerr << "Error in array limits: " << i << "is out of range\n";
  34. exit(EXIT_FAILURE);
  35. }
  36. return ar[i];
  37. }
  38. #endif //PRO1_ARRAYTP_H

arraytp.cpp

  1. #include "arraytp.h"

数字模板的使用范例

main.cpp

  1. #include <iostream>
  2. #include "module11_class_template/arrry/arraytp.h"
  3. using namespace std;
  4. // 数组模板的使用
  5. void useArrayTemplate(){
  6. ArrayTP<int, 10> sums;
  7. ArrayTP<double , 10> aves;
  8. ArrayTP<ArrayTP<int, 5>, 10> twodee;
  9. int i, j;
  10. for (int i = 0; i < 10; i++) {
  11. sums[i] = 0;
  12. for (int i = 0; i < 5; i++) {
  13. twodee[i][j] = (i + 1)*(j + 1);
  14. sums[i] += twodee[i][j];
  15. }
  16. aves[i] = (double)sums[i] / 10;
  17. }
  18. for (int i = 0; i < 10; i++) {
  19. for (int i = 0; i < 5; i++) {
  20. cout.width(2);
  21. cout << twodee[i][j] << ' ';
  22. }
  23. cout << " :sum = ";
  24. cout.widen(3);
  25. cout << sums[i] << ", average = " << aves[i] << endl;
  26. }
  27. cout << "Done.\n";
  28. }
  29. int main() {
  30. useArrayTemplate();
  31. return 0;
  32. }