530 likes | 1.13k Views
Introducing Templates and Generics in C++. CSC 331 20081027. Overview. Value of templates Generic functions Generic classes. Value of templates. Added to original C++ specification Valuable in the creation of reusable code
E N D
Introducing Templates and Generics in C++ CSC 331 20081027
Overview • Value of templates • Generic functions • Generic classes
Value of templates • Added to original C++ specification • Valuable in the creation of reusable code • Used to create generic functions and classes • In which the type of data acted upon is specified as a parameter • Allows one function or class to act on several different types of data without having to code specific versions for each type.
Example generic function swapargs() template <class X> void swapargs (X &a, X &b) { X temp; temp = a; a=b; b=temp; }
Example main using swapargs() int main() { int I =10, j=20; double x=10.1, y=23.3; char a=‘x’, b=‘z’; cout<<“Original i, j “<<i<<‘ ‘<<j<<‘\n’; cout<<“Original x,y “<<x<<‘ ‘<<y<<‘\n’; cout<<“Original a,b “<<a<<‘ ‘<<b<<‘\n’; swapargs(i, j); swapargs(x, y); swapargs(a, b); cout<<“Swapped i, j “<<i<<‘ ‘<<j<<‘\n’; cout<<“Swapped x,y “<<x<<‘ ‘<<y<<‘\n’; cout<<“Swapped a,b “<<a<<‘ ‘<<b<<‘\n’; return 0; }
What happens? • “template” preceding the function definition tells the compiler to create a generic (or template) function. • “X” is a placeholder for the generic type. • In main(), swapargs() is called using 3 different types of data. • This causes the compiler to generate 3 different versions of swapargs(), each for a different type. • Called “generic functions” or “specialized functions.” • Act of generating referred to as “instantiating.”
More about generic functions • More than one placeholder type may be declared for a function. • The keyword class to specify a generic type is traditional, but keyword typenamemay also be used. • Generic functions may be overridden for “explicit specialization.” • Example: void swapargs(int &a, int &b) • This “hides” the generic swapargs() only for ints. • Alternative syntax: template<> void swapargs<int> (int &a, int &b) • Generic functions may be overloaded (different parameter lists).
Generic class: object creation • To create a specific instance of a generic class: • class-name <type> ob; • For previous examples: • queue<int> a, b; // creates 2 integer queues • myClass<int, double> ob1(10, 0.23);
Example generic class #include <iostream> using namespace std; template <class Type1, class Type2> class myClass { Type1 i; Type2 j; public: myClass(Type1 a, Type2 b){i=a; j=b;} void show() {cout<<i<<' '<<j<<'\n';} }; int main() { myClass<int, double>ob1(10, 0.23); myClass<char, char *>ob2('X', "This is a test"); ob1.show(); // show int, double ob2.show(); // show char, char * system("pause"); return 0; }