"5:Wolfgang Kibble", "6:Portia Koop",
"7:Joy Almondo", "8:Xaverie Parika",
"9:Juan Moore", "10:Misha Mache"
};
// out basket
const char* out[ NUM ];
int processed = 0;
int nextin = 0;
while ( processed < NUM )
{
if ( st.isEmpty() )
{
st.push( in[ nextin++ ] );
}
else if ( st.isFull() )
{
st.pop( out[ processed++ ] );
}
else if ( rand() % 2 && nextin < NUM )
{
st.push( in[ nextin++ ] );
}
else
{
st.pop( out[ processed++ ] );
}
}
for ( int i = 0; i < NUM; i++ )
{
cout << out[ i ] << endl;
}
cout << "Done." << endl;
return 0;
}
数组模板范例和非类型参数
模板常被用作容器类,这是因为类型参数的概念非常适合于将相同的存储方案用于不同的类型。确实,为容器类提供可重用代码是引入模板的主要动机。
比如Array
可以将用于常规类的技术用于模板类。模板类可用作基类,也可用作组件类,还可用作其他模板的类型参数。
1.递归使用模板
[cpp]
// testTemplate2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "string"
template
class MyArray
{
public:
MyArray(){}
explicit MyArray( const T& v );
public:
virtual T& operator[]( int i );
virtual T operator[]( int i ) const;
private:
T ar[ n ];
};
template
MyArray
{
for ( int i = 0; i < n; i++ )
{
ar[ i ] = v;
}
}
template
T& MyArray
{
if ( i < 0 || i >= n)
{
cerr << "Error in array limits:" << i << " is out of range" << endl;
exit( EXIT_FAILURE );
}
return ar[ i ];
}
template
T MyArray
{
if ( i < 0 || i >= n)
{
cerr << "Error in array limits:" << i << " is out of range" << endl;
exit( EXIT_FAILURE );
}
return ar[ i ];
}
int _tmain(int argc, _TCHAR* argv[])
MyArray
MyArray
MyArray< MyArray
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;
}
cout << "Done." << endl;
return 0;
}
MyArray< MyArray
2.模板中使用多个类型参数
模板可以保护多个类型参数。例如,假设希望类可以保存两种值,则可以创建并使用Pair模板来保存两个不同的值(标准模板库提供了类似的模板,名为pair)。
[cpp]
// testPair.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "iostream"
using namespace std;
#include "string"
template
class CPair
{
public:
CPair(){}
CPair( const T1& aval, const T2 bval ) : a( aval ), b( bval )
{
}
public:
T1& first()
{
return a;
}
T2& second()
{
return b;
}
T1& first() const { return a }
T2& second() const { return b }
private:
T1 a;
T2 b;
};
int _tmain(int argc, _TCHAR* argv[])
{
CPair
{
CPair
CPair
CPair
CPair
};
int joins = sizeof( ratings ) / sizeof( CPair
cout << "Raring:\tEatery\n";
for ( int i = 0; i < joins; i++ )
{
cout << ratings[ i ].second() << ":\t" << ratings[ i ].first() << endl;
}
cout << "Oops ! Revised rating:" << endl;
ratings[ 3 ].first() = "Gertie's Fab Eat";
ratings[ 3 ].second() = 6;
cout << ratings[ 3 ].second() << ":\t" << ratings[ 3 ].first() << endl;
cout << "Done." << endl;
return 0;
}
模板的具体化
类模板与函数模板很相似,因为