Everything You Need to Know About Templates in C++

C++ is one of the most popular programming languages worldwide. Like other programming languages, it also provides different ways to create functions to perform different tasks through the code. These functions in C++ are specific to the data type you pass in as arguments. But there might be scenarios when a programmer would need generic programming, and that’s where templates in C++ come into the picture. For instance, a programmer might need to use a sort() function to sort data of different types. Usually, the programmer would have to create and use other functions for each data type. The templates in C++ help overcome this challenge.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

What Are Templates in C++?

Templates in C++ act as the foundation of generic programming. It is a simple yet powerful tool that basically acts like a blueprint for creating generic functions or classes. While using a template in C++, you pass a data type as a parameter. Thus, instead of maintaining multiple codes, you have to write one code and give the data type you want to use. C++ templates use two primary keywords, ‘template’ and ‘typename,’ where the ‘typename’ can be replaced with the ‘class’ keyword.

How Do C++ Templates Work?

The templates in C++ are expanded during compile-time. At the very core, they work like macros except for a single significant difference. Unlike macros, the type checking in C++ templates is done before template expansion. This allows the compiled code to have multiple copies of the same class.

What Are Function Templates in C++?

You use C++ function templates for creating functions that can be used with different data types. A function template is used to perform the same function on multiple data types. An alternative approach to this is using function overloading. However, using a function template is the better approach to writing less and more maintainable code. The basic syntax of a function template is:

template <class type> ret-type func-name(parameter_list) {

   // body of function

}

In the syntax mentioned above, type is just a placeholder that the compiler will automatically replace with the actual data type. The keyword class in the syntax is used to specify a generic type and be replaced by a typename.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

Example: Declaring a Function Template in C++

In the below example, you must create a function template in C++ and use it to find the larger value for different data types.

#include <iostream>

using namespace std;

template <class Ttype>

Ttype MaxVal(Ttype i, Ttype j){

    return (i > j)? i: j;

}

int main(){

    cout << MaxVal<int>(5, 8) << endl; // Call myMax for int

    cout << MaxVal<double>(6.5, 4.0) << endl; // call myMax for double

    cout << MaxVal<char>('f', 'k') << endl; // call myMax for char

return 0;

}

Output

Templates_in_Cpp_1

What Are Class Templates in C++?

The class templates in C++ make the class using it generic. It operates similarly to function templates except that it is used on the entire class instead of a single function. The basic syntax of declaring a class template is:

template<class type>

class class_name

{

.

.

}

Once the class is created, you can declare the data type while declaring the class instance.

Example: Declaring a Class Template in C++

#include <iostream>

using namespace std;

template <class Ttype>

class Array{

private:

Ttype *pointr;

int size;

public:

Array(Ttype arr[], int s);

void print();

};

template <class Ttype>

Array<Ttype>::Array(Ttype arr[], int s) {

pointr = new Ttype[s];

size = s;

for(int i = 0; i < size; i++)

pointr[i] = arr[i];

}

template <class Ttype>

void Array<Ttype>::print() {

for (int i = 0; i < size; i++)

cout<<" "<<*(pointr + i);

cout<<endl;

}

int main(){

int arr[5] = {1, 2, 3, 4, 5};

Array<int> a(arr, 5);

a.print();

return 0;

}

Output

Templates_in_Cpp_2

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Passing Multiple Arguments to Templates in C++

Similar to normal functions and classes, you can pass multiple data types as arguments to templates. Now, look at an example that takes multiple arguments.

#include<iostream>

using namespace std;

template<class Ttype, class Utype>

class A{

Ttype x;

Utype y;

public:

A(){ cout<<"The Constructor is Called"<<endl; }

};

int main() {

A<char, char> a;

A<int, double> b;

return 0;

}

Output

Templates_in_Cpp_3.

How to Specify Default Arguments for Templates in C++?

Similar to normal parameters, you can specify default arguments for templates. Here’s an example to demonstrate specifying a default argument for templates in C++.

#include<iostream>

using namespace std;

template<typename Ttype, typename Utype = char>

class Example{

public:

Ttype i;

Utype j;

Example() { cout<<"The Constructor is Called"<<endl; }

};

int main() {

Example<char> a;

return 0;

}

Output

Templates_in_Cpp_4.

What Is the Difference Between Function Overloading and Templates in C++?

Like function overloading, templates in C++ also allow polymorphism. However, there is a fundamental difference between the two. You use the function overloading when you want to perform similar operations. On the other hand, templates in C++ are used to perform precisely identical operations on different data types.

Free Course: Programming Fundamentals

Learn the Basics of ProgrammingEnroll Now
Free Course: Programming Fundamentals

What Is Template Specialization?

Template specialization in C++ is to declare different codes or behavior for a specific data type. This means you can create a specialized version of a function when executed with a particular data type. The code depicted below demonstrates the use of template specialization in C++.

#include <iostream>

using namespace std;

template <typename Ttype>

void Example(Ttype t)

{

cout << "The standard example template: "

<< t << endl;

}

template<>

void Example(int t)

{

cout << "Specialized example template for int: "

<< t << endl;

}

int main()

{

Example<char>('x');

Example<int>(12);

Example<float>(15.30);

}

Output

Templates_in_Cpp_5.

As you can see in the output, the template is executed similarly for char and float data types but differently for the int data type.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

In this article, you have learned everything about templates in C++. You also looked into examples for both types of templates: function and class. You created your templates and used them to execute them with different data types. 

You can use the templates in C++ to achieve a special kind of polymorphism. If you are new to C++ programming and interested in learning about other fundamental concepts of C++, you can refer to our C++ Tutorial for Beginners. The tutorial is specifically designed for beginners and contains guides for various basic concepts. To put it simply, the tutorial is well adept at helping you excel in the field of C++ programming. Enroll in Simplilearn’s  Full Stack Web Development Program to learn modern coding techniques with bootcamp-level intensity.

Have any questions for us? Leave them in the comments section of this write-up, and our experts will get back to you on the same, as soon as possible.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.