12.5 C++实现模板的递归使用
实现模板的递归使用,就是模板的类型是模板。
12.5.1 代码
arraytp.h
main.h
#pragma once
#ifndef MAIN_H_
#define MAIN_H_
#include <iostream> //输入输出
#include "arraytp.h" //template_recursion
using namespace std;
void template_recursion(void)
{
//实现模板的递归使用,就是模板的类型是模板
std::cout << "\ntemplate_recursion Hello*****************************************************\n";
ArrayTP<int, 10> sums;
ArrayTP<double, 10> aves;
ArrayTP< ArrayTP<int, 5>, 10> twodee;//就像是一个二维数组一样使用
int i, j;
for (i = 0; i < 10; i++)
{
sums[i] = 0;
for (j = 0; j < 5; j++)
{
twodee[i][j] = (i + 1) * (j + 1);
sums[i] += twodee[i][j];
}
aves[i] = (double)sums[i] / 10;
}
for (i = 0; i < 10; i++)
{
for (j = 0; j < 5; j++)
{
cout.width(2);
cout << twodee[i][j] << ' ';
}
cout << ": sum = ";
cout.width(3);
cout << sums[i] << ", average = " << aves[i] << endl;
}
std::cout << "template_recursion Bye*****************************************************\n";
}
#endif
main.cpp
/*
Project name : _12template
Last modified Date: 2022年5月6日11点33分
Last Version: V1.0
Descriptions: 实现模板的递归使用
*/
#include "main.h"
int main()
{
cout << "实现模板的递归使用************************************************************" << endl;
template_recursion();
return 0;
}
12.5.2 运行结果
实现模板的递归使用************************************************************
template_recursion Hello*****************************************************
1 2 3 4 5 : sum = 15, average = 1.5
2 4 6 8 10 : sum = 30, average = 3
3 6 9 12 15 : sum = 45, average = 4.5
4 8 12 16 20 : sum = 60, average = 6
5 10 15 20 25 : sum = 75, average = 7.5
6 12 18 24 30 : sum = 90, average = 9
7 14 21 28 35 : sum = 105, average = 10.5
8 16 24 32 40 : sum = 120, average = 12
9 18 27 36 45 : sum = 135, average = 13.5
10 20 30 40 50 : sum = 150, average = 15
template_recursion Bye*****************************************************
D:\Prj\_C++Self\_12template\Debug\_12template.exe (进程 5972)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .