90 likes | 233 Views
Templates. a way of writing generic code. Questions about Templates. what is a template? why are templates needed? how is a function template declared? what does this function prototype mean: template<class T> void myfunc(int*,const T&, T*);
E N D
Templates a way of writing generic code
Questions about Templates • what is a template? • why are templates needed? • how is a function template declared? • what does this function prototype mean: template<class T> void myfunc(int*,const T&, T*); • how does the compiler figure out what class/type to substitute for the template parameter? • how is templated function invoked? • is template an executable statement?
Why Templates • certain code operates similarly regardless of type • example: swapping two values • templates parameterize type and allow writing generic code
Standalone Function Templates • function head/prototype are preceded by template <class typeParameter> • style convention – always put on separate line • example template <class T> void print_stuff(int a, T b, T c); • type parameter may be passed by reference/returned/declared constant template <class T> void show_stuff(int, T&, const T&); • in definition template <class T> void show_stuff(int a, T& b, const T& c){ cout << a << b << c; }
Template Invocation • invoked as ordinary function double one=3.5, two=5.6; string str1="one", str2="two"; show_stuff(1, one, two); show_stuff(3, str1, str2); • templates are not executable code • compiler generates executable code when it sees function invocation. This is called template instantiation • the type parameter is determined by the types of the arguments • can be placed in headers
Class Templates • class definition is preceded by template <class typeParameter> • example template <class T> myclass{ private: int a; T b; T *c; }; • member functions can be declared inline or outside template <class T> void myclass<T> show_stuff(int, T&, const T&);
Member Function Definition • member functions can be defined • inline template <class T> yourclass{ public: int geta() const{return a;}; T getb() const; void setc(T *const); private: int a; T b; T *c; }; • or outside – use scope resolution operator and template keyword template<class T> T yourclass<T>::getb() const { return b; }
Object Declaration and Usage • to use template - declare an object of the class, have to explicitly specify type parameter yourclass<double> d1, *pd1; • methods are invoked as on ordinary objects pd1=&d1; cout << d1.geta(); cout << pd1->getb(); • class templates are not executable, compiler instantiates class templates when objects are declared, methods are instantiated when invoked • put class templates in header files