In this tutorial, you will learn the basics of Templates in C++. You will understand what templates are, why they are useful, and how to use them in your programs. We will cover different types of templates and how they help in writing reusable and flexible code. You will also see real-world examples to make the concept clear and easy to understand.
Contents:
- What are Templates in C++?
- Function Templates in C++
- Class Templates in C++
- Function Templates vs. Class Templates in C++
- Template Specialization in C++
- Variadic Templates in C++
- Template Instantiation in C++
- Advantages of Using Templates in C++
- FAQs on Templates in C++
What are Templates in C++?
Templates in C++ let you write code that works with different data types without writing it again. They help functions and classes use different types of data with just one version of the code.
Why Use Templates?
- Reuse Code: Write one function or class and use it for different data types.
- Safe to Use: Finds type mistakes before running the program.
- Better Efficiency: Avoids repeating code and makes it easier to manage.
Types of Templates:
- Function Templates
- Class Templates
Function Templates in C++
A function template in C++ is used to create a single function that can work with different types of data without rewriting it for every type.
Syntax of Function Template
template <typename T> return_type function_name(T arg1, T arg2) { // Function body }
- template – Keyword to define a template.
- typename T – Declares T as a template parameter. class can also be used instead of typename.
- function_name() – Name of the function.
- arg1, arg2 – Function arguments of type T.
Example: Template to Swap Two Sanfoundry Course IDs
#include <iostream> using namespace std; // Template to swap Sanfoundry Course IDs template <typename T> void swapCourseIDs(T &course1, T &course2) { T temp = course1; course1 = course2; course2 = temp; } int main() { int courseID1 = 101, courseID2 = 202; swapCourseIDs(courseID1, courseID2); cout << "Swapped Course IDs: " << courseID1 << " and " << courseID2 << endl; string courseA = "C++", courseB = "Java"; swapCourseIDs(courseA, courseB); cout << "Swapped Courses: " << courseA << " and " << courseB << endl; return 0; }
Output:
Swapped Course IDs: 202 and 101 Swapped Courses: Java and C++
This C++ program shows how to use templates to create a swap function that works with different data types. The function swapCourseIDs takes two values of any type and swaps them using a temporary variable. In the main function, this template swaps both numbers (101 and 202) and words (“C++” and “Java“). The output shows that the function works for both types. Using templates makes the code simple, reusable, and flexible, so you don’t have to write separate functions for different data types.
Class Templates in C++
A class template in C++ allows creating a blueprint for classes that can work with different data types, enabling code reusability and flexibility.
Syntax:
template <class T> class ClassName { // Class members and methods };
Example: Class Template to Store Quiz Scores
#include <iostream> using namespace std; // Template class to handle Sanfoundry quiz scores template <class T> class SanfoundryQuiz { private: T score1, score2; public: // Constructor to initialize quiz scores SanfoundryQuiz(T s1, T s2) { score1 = s1; score2 = s2; } // Calculate and display average score void displayAverage() { cout << "Average Sanfoundry Quiz Score: " << (score1 + score2) / 2 << endl; } }; int main() { // Integer quiz scores SanfoundryQuiz<int> quiz1(85, 90); quiz1.displayAverage(); // Floating-point quiz scores SanfoundryQuiz<double> quiz2(87.5, 92.3); quiz2.displayAverage(); return 0; }
Output:
Average Sanfoundry Quiz Score: 87 Average Sanfoundry Quiz Score: 89.9
This C++ program uses templates to create a class for quiz scores of different types. The SanfoundryQuiz class stores two scores and has a function to find the average. The main function creates objects for integer scores (85, 90) and decimal scores (87.5, 92.3). The program prints the average for both. Using templates makes the class flexible and easy to reuse, so it works with different types of numbers.
Function Templates vs. Class Templates in C++
Here is a comparison table between Function Templates and Class Templates in C++:
Feature | Function Templates | Class Templates |
---|---|---|
Definition | Used to create generic functions. | Used to create generic classes. |
Purpose | Allows writing a single function that works with multiple data types. | Allows defining a class that works with different data types. |
Usage | Works with functions (e.g., swapping, sorting). | Works with classes (e.g., data structures, objects). |
Syntax | template <typename T> returnType functionName(T param) {…} | template <typename T> class ClassName {…} |
Example Usage | Swapping two numbers, finding the maximum of two values. | Creating a stack, handling quiz scores. |
Example Code | template <typename T> void swap(T &a, T &b) {…} | template <typename T> class Box { T value; … }; |
Flexibility | Used when only one function needs to be generic. | Used when multiple functions within a class need to be generic. |
Instances Needed | No need to create an object to use the function. | Requires creating an object of the class template. |
Template Specialization in C++
Template Specialization allows us to create a specialized version of a template for a specific data type. It helps customize the behavior of a generic template when used with particular types.
1. Function Template Specialization in C++
Function Template Specialization allows the definition of a special version of a function template for a specific type.
Syntax:
template <class T> return_type FunctionName(T arg) { // General template } // Specialization for a specific data type template <> return_type FunctionName<special_type>(special_type arg) { // Specialized version for special_type }
Example: Function Template Specialization
#include <iostream> using namespace std; // General template template <class T> void evaluateScore(T score) { cout << "General Evaluation: Score is " << score << endl; } // Specialized template for string template <> void evaluateScore<string>(string feedback) { cout << "Sanfoundry Certification Feedback: " << feedback << endl; } int main() { // General template for int evaluateScore(95); // General template for float evaluateScore(88.5); // Specialized template for string evaluateScore<string>("Excellent Certification Program!"); return 0; }
Output:
General Evaluation: Score is 95 General Evaluation: Score is 88.5 Sanfoundry Certification Feedback: Excellent Certification Program!
This C++ program shows template specialization, where one function works for many data types, but a special version is made for string. The general function prints scores for numbers, while the special function gives feedback for text. In the main function, numbers use the general function, and a text message uses the special one. This makes the code simple, flexible, and easy to reuse.
2. Class Template Specialization in C++
Class Template Specialization creates a specialized version of a class template to provide custom functionality for specific data types.
Syntax:
template <class T> class ClassName { // General template }; // Specialization for a specific data type template <> class ClassName<special_type> { // Specialized template };
Example: Class Template Specialization
#include <iostream> using namespace std; // General template template <class T> class SanfoundryFeedback { public: SanfoundryFeedback(T feedback) { cout << "General Feedback: " << feedback << endl; } }; // Specialized template for string template <> class SanfoundryFeedback<string> { public: SanfoundryFeedback(string feedback) { cout << "Sanfoundry Internship Feedback: " << feedback << endl; } }; int main() { // General template with int SanfoundryFeedback<int> feedback1(5); // General template with float SanfoundryFeedback<float> feedback2(4.9); // Specialized template with string SanfoundryFeedback<string> feedback3("Excellent Internship!"); return 0; }
Output:
General Feedback: 5 General Feedback: 4.9 Sanfoundry Internship Feedback: Excellent Internship!
This C++ program shows class template specialization, where one class works for many data types, but a special version is made for string. The general class prints feedback for numbers like int and float, while the special class prints feedback for text. In the main function, numbers (5 and 4.9) use the general class, and a text message (“Excellent Internship!”) uses the special one.
Variadic Templates in C++
Variadic templates in C++ allow a function or class to accept and process a variable number of template arguments. This feature provides flexibility to work with multiple arguments of different types.
Syntax:
template <typename... Args> class ClassName { // Class body }; template <typename... Args> return_type function_name(Args... args) { // Function body }
Example:
#include <iostream> using namespace std; // Variadic template to print all arguments template <typename... Args> void registerCourses(Args... courses) { cout << "Sanfoundry Course Registration:" << endl; ((cout << courses << endl), ...); // Fold expression to print each argument } int main() { // Registering multiple courses registerCourses("C++", "Java", "Python", "Data Structures"); return 0; }
Output:
Sanfoundry Course Registration: C++ Java Python Data Structures
This C++ program shows variadic templates, which let a function take many arguments of different types. The registerCourses function takes many course names and prints them. A fold expression (cout << ... << courses << endl) helps print all names quickly. In the main function, registerCourses is used with “C++”, “Java”, “Python”, “Data Structures”, and they are printed. This makes the function simple, efficient, and easy to use.
Template Instantiation in C++
Template instantiation is the process of creating a specific version of a template function or class by substituting the template parameters with actual types or values.
Types of Template Instantiation:
- Implicit Instantiation: The compiler automatically generates the required version of the template when it is used.
- Explicit Instantiation: The programmer explicitly tells the compiler to generate a specific instance of the template.
Implicit Instantiation Example
#include <iostream> using namespace std; // Template to calculate average marks template <typename T> T calculateAverage(T marks1, T marks2) { return (marks1 + marks2) / 2.0; } int main() { // Implicit instantiation for int and float cout << "Average (int): " << calculateAverage(90, 80) << endl; cout << "Average (float): " << calculateAverage(85.5, 90.0) << endl; return 0; }
Output:
Average (int): 85 Average (float): 87.75
This C++ program uses a function template to find the average of two marks. The calculateAverage function works with int and float. It adds two numbers and divides by 2.0. In main, it calculates averages for 90, 80 and 85.5, 90.0.
Explicit Instantiation Example
#include <iostream> using namespace std; // Template to calculate total marks template <typename T> T totalMarks(T marks1, T marks2) { return marks1 + marks2; } // Explicit instantiation for int and float template int totalMarks<int>(int, int); template float totalMarks<float>(float, float); int main() { cout << "Total Marks (int): " << totalMarks(75, 85) << endl; cout << "Total Marks (float): " << totalMarks(88.5f, 92.0f) << endl; return 0; }
Output:
Average (int): 85 Average (float): 87.75 Total Marks (int): 160 Total Marks (float): 180.5
This C++ program uses a function template to find total marks. The totalMarks function works with int and float. It adds two numbers and gives the result. Explicit instantiation makes sure the function works for int and float. In main, it adds 75, 85 (integers) and 88.5f, 92.0f (floats).
Advantages of Using Templates in C++
- Code Reusability – Templates let you write one function or class for different data types, reducing extra code and making maintenance easier.
- Type Safety – The compiler checks data types, stopping errors from wrong type conversions.
- Better Performance – Templates work at compile time, avoiding extra processing and making the program faster.
- Works with Many Data Types – A single template can handle different data types, making coding simpler.
- Supports Generic Data Structures – Templates help build standard data structures like vectors, maps, and sets in the STL.
- Scalability – Templates make the code flexible, so it can easily handle new data types.
- Faster Development – Templates save time by reducing repeated code, making programming quicker and more efficient.
FAQs on Templates in C++
1. What are templates in C++?
Templates allow writing generic code that works with multiple data types, enabling code reusability and flexibility.
2. What are the types of templates in C++?
There are two main types:
- Function Templates – Define generic functions that work with different data types.
- Class Templates – Define generic classes, like containers in STL (vector, map).
3. Why use templates in C++?
Templates improve code reusability, type safety, performance, and scalability, reducing the need for redundant code.
4. What is template specialization?
Template specialization allows defining a custom implementation of a template for a specific data type.
5. What is variadic templates in C++?
Variadic templates allow a function or class to accept an arbitrary number of parameters, making it highly flexible.
6. What is template instantiation?
It is the process of creating a concrete version of a template for a specific type, either implicitly (automatically) or explicitly (forced).
7. Are templates faster than polymorphism?
Yes, templates are resolved at compile-time, eliminating runtime overhead, while polymorphism uses virtual functions, which have a small performance cost.
Key Points to Remember
Here is the list of key points we need to remember about “Templates in C++”.
- Templates in C++ allow writing generic code that works with multiple data types, improving reusability and flexibility.
- Function templates enable defining a single function that operates on different data types without rewriting it.
- Class templates help create generic classes, making it easier to develop reusable data structures.
- Template specialization customizes behavior for specific data types while maintaining general template functionality.
- Variadic templates allow handling multiple arguments of different types efficiently.
- Template instantiation generates specific versions of templates, either implicitly by the compiler or explicitly by the programmer.
- Using templates enhances code efficiency by reducing redundancy and ensuring type safety at compile time.
- Templates are widely used in the Standard Template Library (STL) to implement data structures like vectors, sets, and maps.