A template function is a function that can operate on a generic datatype, which will allow you to use the same function on many different types of data.
The expression:
template< class T >
returntype functionname( parameter list)
Example:
template< class T >
T Sum( T* p_array, int p_count )
{
int index;
T sum = 0;
for (index = 0; index < p_count; ++index)
sum += p_array[index];
return sum;
}
A template class is similar to a template function, except that a template class is an entire class that operates on a generic datatype.
Example:
template< class T >
class Adder
{
public:
// constructor
Adder()
{
m_sum = 0;
}
// add function
void Add( T p_number )
{
m_sum += p_number;
}
// get sum function
T Sum()
{
return m_sum;
}
private:
// sum variable
T m_sum;
};
Multiple parameterized types
A template class or function can have any number of parameterized types.
The expression:
template< class one, class two, class three >
Example:
template< class Sumtype, class Averagetype >
Averagetype Average( Sumtype* p_array, Averagetype p_count )
{
int index;
Sumtype sum = 0;
for (index = 0; p_count > index; index++ )
sum += p_array[index];
return (Averagetype)sum / p_count;
}
Using values as template parameters
C++ allows you to use values of a particular datatype as template parameters.
The expression:
template< datatype value >
Example:
template< class Datatype, int size >
class Array
{
Public:
// set function, sets an index
void Set( Datatype p_item, int p_index )
{
m_array[p_index] = p_item;
}
// get function, gets an index
Datatype Get( int p_index )
{
return m_array[p_index];
}
private:
// the array
Datatype m_array[size];
}
;
Using values of other parameterized types
The expression:
template< class T, T value>
Example:
template< class Datatype, int size, Datatype zero >
class Array
{
Public:
// set function, sets an index
void Set( Datatype p_item, int p_index )
{
m_array[p_index] = p_item;
}
// get function, gets an index
Datatype Get( int p_index )
{
return m_array[p_index];
}
// clear the array
void Clear( int p_index )
{
m_array[p_index] = zero;
}
private:
// the array
Datatype m_array[size];
}
;
Problems with templates:
The number of things you can do with a template is somewhat limited.
本文出自 “第二次启航” 博客,谢绝转载!