Presentation is loading. Please wait.

Presentation is loading. Please wait.

Templates CS-341 Dick Steflik. Reuse Templates allow us to get more mileage out of the classes we create by allowing the user to supply certain attributes.

Similar presentations


Presentation on theme: "Templates CS-341 Dick Steflik. Reuse Templates allow us to get more mileage out of the classes we create by allowing the user to supply certain attributes."— Presentation transcript:

1 Templates CS-341 Dick Steflik

2 Reuse Templates allow us to get more mileage out of the classes we create by allowing the user to supply certain attributes at compile time. Attributes are specified in the template definition and are resolved by doing text substitutions by the compiler preprocessor Think of it like doing text “replaces” in a work processor

3 Template Functions Isn’t really a function, design of a function starts off with Template –in the function occurrences of text will be replaced with actual type of submitted parameter multiple substitutions can be specified by using

4 Template Function template T sum3 ( T a, T b, T c) { return (a+b+c); } int main ( ) { int l,m,n; double r,s,t; /* use sum3 to sum sets variables of different types */ cout << sum3 (l,m,n) << “ “ << sum3 (r,s,t); }

5 Template class like a function template is not a function a template class is not a class, but it is the instructions for the compiler on how to define the class template parameters are specified the same as for Template functions text substitutions are done explicitly not implicitly like template functions

6 General Form of a Template class

7 General Form of a Template Class template class templateClass { public: // constructor templateClass (const T& item); // member functions T f( ); void g (const T& item); private: T dataValue; … };

8 MemoryCell Template class template class MemoryCell { public: /* constructor */ explicit MemoryCell( const T & initVal = T()) : storedValue(initValue){} /* accessor functions */ const T & read ( ) const { return storedValue; } void write (const T & x) { storedValue = x; } private: T storedValue; }

9 MemoryCell class Notice, previous example use “inline” code to define the class Notice also that the syntax is slightly different The next example separates into interface and implementation

10 MemoryCell interface template class MemoryCell { public: explicit MemoryCell (const T & initVal = T( )); const T & read( ) const; void write (const T & x); private: T storedValue; }

11 MemoryCell implementation #include “MemoryCell.h” template MemoryCell :: MemoryCell (const T & initVal) : storedValue(initVal) { } templat const T & MemoryCell :: read ( ) const { return storedValue; } template void MemoryCell :: write (const T & x) { storedValue = x ;}


Download ppt "Templates CS-341 Dick Steflik. Reuse Templates allow us to get more mileage out of the classes we create by allowing the user to supply certain attributes."

Similar presentations


Ads by Google