C++实现模板的递归使用

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。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jasmine-Lily

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值