You are on page 1of 20

Templates in C++

• A template is a simple very powerful tool in C++. The simple idea is to


pass the data type as a parameter so that we don’t need to write the
same code for different data types. We can draw any logic using C++
template.
• C++ adds two new keywords to support templates: ‘template’ and
‘type name’. The second keyword can always be replaced by the
keyword ‘class’.
How Do Templates Work?
• Templates are expanded at compiler time.
• The difference is, that the compiler does type-checking before
template expansion. The idea is simple, source code contains only
function/class, but compiled code may contain multiple copies of the
same function/class.
• We have to type of templates in c++.
• 1)function Template(Generic function)
• 2)Class template(Generic class)
Syntax for Generic Function:
• template <class type>
• return-type func-name(parameter list)
• {
• // body of function
•}
Example:
• #include <iostream>
• #include <string>
using namespace std;
template <typename T> OR // function template
template <class T>
inline T Max (T a, T b) {
return a < b ? b:a;
}
• int main () {
• int i = 40;
• int j = 25;
• cout << "Max(i, j): " << Max(i, j) << endl;
• double d1 = 29.56;
• double d2 = 20.43;
• cout << "Max(d1, d2): " << Max(d1, d2) << endl;
• string s1 = "Hello";
• string s2 = “class";
• cout << "Max(s1, s2): " << Max(s1, s2) << endl;
• return 0;
•}
C++ Program to Swap data using function
template:
• #include <iostream>
• using namespace std;

• template <typename T>


• void Swap(T &n1, T &n2)
•{
• T temp;
• temp = n1;
• n1 = n2;
• n2 = temp;
•}
• int main()
•{
• int i1 = 7, i2 = 9;
• float f1 = 79.2, f2 = 14.5;
• char c1 = ‘y', c2 = 'x’;
Swap(i1, i2);
• Swap(f1, f2);
• Swap(c1, c2);
• Return 0;

•}
Function template overloading:
• using namespace std;
• template <class T>

• void display(T x, T y)
•{
• cout << "Displaying Template: "
• << "\n";
•}
• void display(int x, T y, T z)
•{
• cout << "Explicitly display: "
• << "\n";
•}

• int main()
•{
• // Function Call with a
• // different arguments
• display(200,564);
• display(12.40,23.45, 34.23);
• return 0;
•}
Syntax for Generic Class:
template <class type> // here type support any type of data type
class class-name
{
Public:
Type Variable;
Type function Name(type argu-list)
}
Example:
• #include <iostream>
• using namespace std;
• template<class T>
• class A
•{
• public:
• T num1 = 5;
• T num2 = 6;
• void add()
• {
• std::cout << "Addition of num1 and num2 : " <<
num1+num2<<std::endl;
• }

• };
• int main()
•{
• A<int> d;
• d.add();
• return 0;
•}
Inheritance in Class template:
• #include <iostream>

• template <typename T>


• class Base{
• public:
• void func(){ // (1)
• std::cout << "func\n";
• }
• };
• template <typename T>
• class Derived: public Base<T>{
• public:
• void callBase(){
• func(); // (2)
• }
• };
• int main(){

• std::cout << '\n';

• Derived<int> derived;
• derived.callBase();

• std::cout << '\n';

•}

You might also like