| I l@ve RuBoard |
|
Exercise 6.1Rewrite the following class definition to make it a class template: class example { public: example( double min, double max ); example( const double *array, int size ); double& operator[]( int index ); bool operator==( const example1& ) const; bool insert( const double*, int ); bool insert( double ); double min() const { return _min; } double max() const { return _max; } void min( double ); void max( double ); int count( double value ) const; private: int _size; double *_parray; double _min; double _max; }; To transform the example class into a template, we must identify and factor out each dependent data type. _size, for example, is of type int. Might that vary with different user-specified instances of example? No. _size is an invariant data member that holds a count of the elements addressed by _parray. _parray, however, may address elements of varying types: int, double, float, string, and so on. We want to parameterize the data type of the members _parray, _min, and _max, as well as the return type and signature of some of the member functions.
template <typename elemType>
class example {
public:
example( const elemType &min, const elemType &max );
example( const elemType *array, int size );
elemType& operator[]( int index );
bool operator==( const example1& ) const;
bool insert( const elemType*, int );
bool insert( const elemType& );
elemType min() const { return _min; };
elemType max() const { return _max; };
void min( const elemType& );
void max( const elemType& );
int count( const elemType &value ) const;
private:
int _size;
elemType *_parray;
elemType _min;
elemType _max;
};
Because elemType now potentially represents any built-in or user-defined class, I declare the formal parameters as const references rather than pass them by value. |
| I l@ve RuBoard |
|