// template6.cpp By: Aiman Hanna - ©1993-2006 Aiman Hanna // This program illustrates how to create and use template classes. // // Key Points: 1) Template classes. #include "template6.h" // Constructor of the template class. template Accumulator< T >::Accumulator( T val ) { total = val; } template void Accumulator< T >::AddValue( T val) { // Increment the private attribute, total, with the given value total += val; } template T Accumulator< T >::GetTotal( void ) { // return the current value of the private attribute, total. return total; } int main() { // Create two objects of the Accumulator class, where the type is integer Accumulator< int > acc1(10), acc2(20); // Create two objects of the Accumulator class, where the type is double Accumulator< double > acc3(2.5), acc4(5.4); acc1.AddValue( 3 ); acc2.AddValue( 4 ); cout << " The total value for acc1 is: " << acc1.GetTotal() << endl << endl; cout << " The total value for acc2 is: " << acc2.GetTotal() << endl << endl; acc3.AddValue( 3.3 ); acc4.AddValue( 4.1 ); cout << " The total value for acc3 is: " << acc3.GetTotal() << endl << endl; cout << " The total value for acc4 is: " << acc4.GetTotal() << endl << endl; return 0; } // The output of the program: /* The total value for acc1 is: 13 The total value for acc2 is: 24 The total value for acc3 is: 5.8 The total value for acc4 is: 9.5 */