テンプレート



「テンプレート」と「関数のオーバーロード」は用途によって使い分ける。

コード

#include	<iostream>

using namespace std;

//
template	<class X>	bool	CompareNumber(X a, X b)
{

	static bool bAns;

	if((a - b) >= 0){
		return true;
	}else{
		return false;
	}

}


//
int	AskLarge(int n1, int n2)
{

	static int nAns;

	if((n1 - n2) >= 0){
		nAns = n1;
	}else{
		nAns = n2;
	}

	return nAns;

}


//
double	AskLarge(double n1, double n2)
{

	static double nAns;

	if((n1 - n2) >= 0){
		nAns = n1;
	}else{
		nAns = n2;
	}

	return nAns;

}


//
void main()
{

	int	i;
	
	//
	cout << CompareNumber(1, 2) << endl;
	cout << CompareNumber(5, 2) << endl;

	//
	double dD[8] = {0.0, 1.0, 5.0, 1.5, -3.0, 5.001, -5.0, -100.1};

	double	dMax;

	dMax = dD[0];

	for(i = 1; i < 8; i++)
	{
		if(CompareNumber(dD[i], dMax)){
			dMax = dD[i];
		}
	}

	cout << "dMax = " << dMax << endl;


	//
	int	nMax;

	nMax = (int)dD[0];

	for(i = 1; i < 8; i++)
	{
		nMax = AskLarge(nMax, (int)dD[i]);
	}

	cout << "nMax = " << nMax << endl;
	

	//
	double	dMax1;

	dMax1 = dD[0];

	for(i = 1; i < 8; i++)
	{
		dMax1 = AskLarge(dMax1, dD[i]);
	}

	cout << "dMax1 = " << dMax1 << endl;

	return;	
}
			


結果

0
1
dMax = 5.001
nMax = 5
dMax1 = 5.001
			

 


<戻る>