C++ Templates
Manimala K
Assistant Professor
Department of Computer Science and Engineering
Government College of Engineering, Salem
Introduction
• A general definition of functions and classes
– Generic classes and Generic functions provides
support for Generic programming
– Further simplifies the previous function
overloading
– Another form of polymorphism
– In a template, the data type is the parameter
– The precise definitions of the template functions
and classes are determined in run-time based on
the data type
Function Templates
• To define function templates used to create a
family of functions with different argument types.
• Consider the following function
int max (int x, int y)
{ return (x > y? x : y); }
• It only works for the int type of variables
• How can we make it work for other types of
variables?
Function Templates (cont.)
• Use function overloading
float max (float x, float y)
{ return (x > y? x : y); }
double max (double x, double y)
{ return (x > y? x : y); }
char max (char x, char y)
{ return (x > y? x : y); }
……
Function Templates (cont.)
• Do we have a smarter way to do that?
• First line called "template prefix“
template <class T>
T max (T x, T y)
{ return (x > y? x : y); }
• Type parameter First line called "template prefix“
Tells compiler what’s coming is "template“ . And
that T is a type parameter
Function Templates (cont.)
• In template <class T>, "class" means "type", or
"classification“. It is NOT the class we learned
before
• To avoid confusion, one can use “type name”.
• T can be replaced by any type in the run time,
predefined or user-defined (like a C++ class type),
in function definition body
• Note: one can use other symbol than "T", but T is
the "traditional" usage
How Does this Work?
• Consider the following example
#include <iostream.h>
template<typename T>
T abs(T x)
{ return x < 0? -x : x; }
void main()
{ int n = -5;
double d = -5.5;
cout << abs(n) << endl;
cout << abs(d) << endl;
return;
}
How Does this Work? (cont.)
Output is:
5
5.5
• If not using template, at least two abs functions
need to be defined:
– one for int type,
– other for double type
• In run-time, compiler determines the actual type
for T based on the type of the input variable
How Does this Work? (cont.)
• For instance, abs(n), n is int type
• The compiler then creates the following function
based on the template
int abs(int x)
{ return x < 0? -x : x; }
• For instance, abs(n), n is double type
• The compiler then creates the following function
based on the template
double abs(double x)
{ return x < 0? -x : x; }
Difference Between Template
Functions and Normal Functions
• Compiler won’t generate instance for template
functions during compiling. It generates when it is
called (see abs example).
• If a template function is used by several other
places in different .cpp files, the template function
and its body need to be put in the .h file not only
the declaration.
• The function pointer can only point to instance of
the template function
Back to the max function
• We now can use template to address our issue
with the max function
#include <iostream.h>
template<class T>
T max(T x, T y)
{ return x > y? x : y; }
void main()
{ int n1 = -5, n2 = 0;
double d1 = -5.5, d2 = -5.9;
cout << max(n1, n2) << endl;
cout << max(d1, d2) << endl;
}
Swap values example
#include <iostream.h>
class ABC
{
private:
float x, y;
public:
ABC(float inx, float iny)
{x=inx; y=iny;}
};
template<class T>
T swap(T &x, T &y)
{ T tmp = x; x = y; y = tmp; }
Swap values example (cont.)
void main()
{ int n1 = -5, n2 = 0;
double d1 = -5.5, d2 = -5.9;
ABC obj1(3, 4.4),obj2(3.1, 0.2);
swap(n1, n2);
swap (d1, d2);
swap (obj1, obj2);
}
We can also use it to swap the values of two objects.
Multiple Type Parameters
• Can have: template<class T1, class T2>
• Not typical Usually only need one "replaceable"
type Cannot have "unused" template parameters
Each must be "used" in definition Error otherwise
Multiple Type Parameters (cont.)
• What is the problem of the following
template functions?
template<class T1, class T2>
T1 max (T1 num1, T1 num1)
{ return num1 > num2 ? num1 : num2; }
T2 min (T2 num1, T2 num2)
{ return num1 > num2 ? num2 : num1; }
• First example T2 is not used.
• Second example Missing a template prefix
What is the output of the following program?
#include <iostream.h>
template<class T>
T max(T x, T y)
{ return x > y? x : y; }
void main()
{ int n1 = -5, n2 = 0;
double d1 = -5.5, d2 = -5.9;
cout << max(n1, d2) << endl;
cout << max(d1, n2) << endl;
}
• Compiling error. T ambiguous…
• How to fix it?
– Use multiple type parameters
Class Templates
• We can also define template class, which can be
considered as the “generalized” classes (i.e., can be
used to generate actual classes in run-time).
template<class T>
class ClassName
{ //T data member;
//memberfunction definition;
};
• Example
template<class T>
class calc
{ public:
T multiply(T x, T y);
T add(T x, T y);
};
template<class T>
T calc<T>::multiply(T x, T y)
{ return x*y; }
template<class T>
T calc<T>::add(T x, T y)
{ return x+y; }
void main()
{ calc<int> c1;
cout<<c1.multiply(10,20);
cout<<c1.add(100,200);
calc<float> c2;
cout<<c1.multiply(10.50,20.75 );
cout<<c1.add(100.66,200.77);
}
Templates and Inheritance
• Nothing new here Derived template classes
Can derive from template or non-template
class
• Derived class is then naturally a template
class Syntax same as ordinary class derived
from ordinary class
Summary Function templates
Class templates
• Define functions with parameter for a type
Class templates
• Define class with parameter for class
are template classes
• Can define template class derived from a
template base class
Exercise
• Write template function to add three numbers and
one user defined data type.
• Write a template function to sort the numbers and
one user defined data type.
• Write a class template for Vector to find maximum,
minimum and sum.
• Write a class template for Array to read, display
and sort methods.
Thank You…

4.1 C++ Template for engineering course. Learn easily

  • 1.
    C++ Templates Manimala K AssistantProfessor Department of Computer Science and Engineering Government College of Engineering, Salem
  • 2.
    Introduction • A generaldefinition of functions and classes – Generic classes and Generic functions provides support for Generic programming – Further simplifies the previous function overloading – Another form of polymorphism – In a template, the data type is the parameter – The precise definitions of the template functions and classes are determined in run-time based on the data type
  • 3.
    Function Templates • Todefine function templates used to create a family of functions with different argument types. • Consider the following function int max (int x, int y) { return (x > y? x : y); } • It only works for the int type of variables • How can we make it work for other types of variables?
  • 4.
    Function Templates (cont.) •Use function overloading float max (float x, float y) { return (x > y? x : y); } double max (double x, double y) { return (x > y? x : y); } char max (char x, char y) { return (x > y? x : y); } ……
  • 5.
    Function Templates (cont.) •Do we have a smarter way to do that? • First line called "template prefix“ template <class T> T max (T x, T y) { return (x > y? x : y); } • Type parameter First line called "template prefix“ Tells compiler what’s coming is "template“ . And that T is a type parameter
  • 6.
    Function Templates (cont.) •In template <class T>, "class" means "type", or "classification“. It is NOT the class we learned before • To avoid confusion, one can use “type name”. • T can be replaced by any type in the run time, predefined or user-defined (like a C++ class type), in function definition body • Note: one can use other symbol than "T", but T is the "traditional" usage
  • 7.
    How Does thisWork? • Consider the following example #include <iostream.h> template<typename T> T abs(T x) { return x < 0? -x : x; } void main() { int n = -5; double d = -5.5; cout << abs(n) << endl; cout << abs(d) << endl; return; }
  • 8.
    How Does thisWork? (cont.) Output is: 5 5.5 • If not using template, at least two abs functions need to be defined: – one for int type, – other for double type • In run-time, compiler determines the actual type for T based on the type of the input variable
  • 9.
    How Does thisWork? (cont.) • For instance, abs(n), n is int type • The compiler then creates the following function based on the template int abs(int x) { return x < 0? -x : x; } • For instance, abs(n), n is double type • The compiler then creates the following function based on the template double abs(double x) { return x < 0? -x : x; }
  • 10.
    Difference Between Template Functionsand Normal Functions • Compiler won’t generate instance for template functions during compiling. It generates when it is called (see abs example). • If a template function is used by several other places in different .cpp files, the template function and its body need to be put in the .h file not only the declaration. • The function pointer can only point to instance of the template function
  • 11.
    Back to themax function • We now can use template to address our issue with the max function #include <iostream.h> template<class T> T max(T x, T y) { return x > y? x : y; } void main() { int n1 = -5, n2 = 0; double d1 = -5.5, d2 = -5.9; cout << max(n1, n2) << endl; cout << max(d1, d2) << endl; }
  • 12.
    Swap values example #include<iostream.h> class ABC { private: float x, y; public: ABC(float inx, float iny) {x=inx; y=iny;} }; template<class T> T swap(T &x, T &y) { T tmp = x; x = y; y = tmp; }
  • 13.
    Swap values example(cont.) void main() { int n1 = -5, n2 = 0; double d1 = -5.5, d2 = -5.9; ABC obj1(3, 4.4),obj2(3.1, 0.2); swap(n1, n2); swap (d1, d2); swap (obj1, obj2); } We can also use it to swap the values of two objects.
  • 14.
    Multiple Type Parameters •Can have: template<class T1, class T2> • Not typical Usually only need one "replaceable" type Cannot have "unused" template parameters Each must be "used" in definition Error otherwise
  • 15.
    Multiple Type Parameters(cont.) • What is the problem of the following template functions? template<class T1, class T2> T1 max (T1 num1, T1 num1) { return num1 > num2 ? num1 : num2; } T2 min (T2 num1, T2 num2) { return num1 > num2 ? num2 : num1; } • First example T2 is not used. • Second example Missing a template prefix
  • 16.
    What is theoutput of the following program? #include <iostream.h> template<class T> T max(T x, T y) { return x > y? x : y; } void main() { int n1 = -5, n2 = 0; double d1 = -5.5, d2 = -5.9; cout << max(n1, d2) << endl; cout << max(d1, n2) << endl; } • Compiling error. T ambiguous… • How to fix it? – Use multiple type parameters
  • 17.
    Class Templates • Wecan also define template class, which can be considered as the “generalized” classes (i.e., can be used to generate actual classes in run-time). template<class T> class ClassName { //T data member; //memberfunction definition; };
  • 18.
    • Example template<class T> classcalc { public: T multiply(T x, T y); T add(T x, T y); }; template<class T> T calc<T>::multiply(T x, T y) { return x*y; } template<class T> T calc<T>::add(T x, T y) { return x+y; }
  • 19.
    void main() { calc<int>c1; cout<<c1.multiply(10,20); cout<<c1.add(100,200); calc<float> c2; cout<<c1.multiply(10.50,20.75 ); cout<<c1.add(100.66,200.77); }
  • 20.
    Templates and Inheritance •Nothing new here Derived template classes Can derive from template or non-template class • Derived class is then naturally a template class Syntax same as ordinary class derived from ordinary class
  • 21.
    Summary Function templates Classtemplates • Define functions with parameter for a type Class templates • Define class with parameter for class are template classes • Can define template class derived from a template base class
  • 22.
    Exercise • Write templatefunction to add three numbers and one user defined data type. • Write a template function to sort the numbers and one user defined data type. • Write a class template for Vector to find maximum, minimum and sum. • Write a class template for Array to read, display and sort methods.
  • 23.