English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn C ++Templates. You will learn how to use the features of templates for generic programming.
Templates are in C ++The powerful features allow you to write generic programs. In short, you can use templates to create a function or a class to handle different data types.
Templates are commonly used in larger codebases to achieve code reusability and program flexibility.
The concept of a template can be used in two different ways:
Function template
Class template
The way function templates work is similar to that of ordinaryFunctionSimilar, but with a difference.
A single function template can handle different data types at once, but a single ordinary function can only handle a set of data types.
Generally, if the same operation needs to be performed on two or more types of data, function overloading can be used to create two functions with the required function declarations.
However, a better method is to use function templates, as you can perform the same task with less code.
Function templates start with the keyword 'template', followed by the template parameters within the <> brackets, and then the function declaration.
template <class T> T someFunction(T arg) { ... ... ... }
In the above code, T is a template parameter that accepts different data types (such as int, float, etc.), andclassis a keyword.
In the above example, you can also use the keyword typename instead of class.
When the data type parameter is passed to someFunction(), the compiler generates a new version of someFunction() for the given data type.
The program uses a function template to display the largest of two numbers.
//If two characters are passed to the function template, it displays the character with the larger ASCII value. #include <iostream> using namespace std; // template function template <class T> T Large(T n1, T n2) { return (n1 > n2) ? n1 : n2; } int main() { int i1, i2; float f1, f2; char c1, c2; cout << "Input two integers:\n"; cin >> i1 >> i2; cout << Large(i1, i2) << " Larger." << endl; cout << "\nInput two floating-point numbers:\n"; cin >> f1 >> f2; cout << Large(f1, f2) << " Larger." << endl; cout << "\nInput two characters:\n"; cin >> c1 >> c2; cout << Large(c1, c2) << " Has a larger ASCII value."; return 0; }
Output results
Enter two integers: 5 10 10 is larger. Enter two floating-point numbers: 12.4 10.2 12.4 is larger. Enter two characters: z Z z has a larger ASCII value.
In the above program, a function template Large() is defined, which accepts two parameters of data type T as n1and n2. T indicates that this parameter can be any data type.
The Large() function uses a simpleConditional operationReturns the largest of the two parameters.
Inside the main() function, three different data type variables are declared: int, float, and char. Then the variables are passed to the Large() function template as regular functions.
At runtime, when an integer is passed to the template function, the compiler knows that a Large() function must be generated to accept an int parameter, and it does so.
Similarly, when passing floating-point and char data, it knows the variable data type and generates the Large() function accordingly.
Thus, with just one function template, you can replace three identical regular functions, making your code less and easier to maintain.
The program uses a function template to swap data.
#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 = 1, i2 = 2; float f1 = 1.1, f2 = 2.2; char c1 = a, c2 = b; cout << "Before passing data to the function template.\n"; cout << "i1 = " << i1 <<< "\ni2 = " << i2; cout << "\nf1 = " << f1 <<< "\nf2 = " << f2; cout << "\nc1 = " << c1 <<< "\nc2 = " << c2; Swap(i1, i2); Swap(f1, f2); Swap(c1, c2); cout << "\n\nAfter passing data to the function template.\n"; cout << "i1 = " << i1 <<< "\ni2 = " << i2; cout << "\nf1 = " << f1 <<< "\nf2 = " << f2; cout << "\nc1 = " << c1 <<< "\nc2 = " << c2; return 0; }
Output results
Before passing data to the function template. i1 = 1 i2 = 2 f1 = 1.1 f2 = 2.2 c1 = a c2 = b After passing data to the function template. i1 = 2 i2 = 1 f1 = 2.2 f2 = 1.1 c1 = b c2 = a
In this program, the function is called not by passing values, butBy referenceMake a call.
The Swap() function template accepts two parameters and swaps them by reference.
Like function templates, you can also create class templates for generic class operations.
Sometimes, you need a class implementation that applies to all classes, but with different data types used.
Typically, you need to create a different class for each data type, or create different member variables and functions within a class.
This will add very similar code and will be difficult to maintain.
However, class templates make it easier to reuse the same code for all data types.
template <class T> class className { ... ... ... public: T var; T someOperation(T arg); ... ... ... };
In the above declaration, T is a template parameter, which is a placeholder for the data type used.
Within the class, both the member variable var and the member function someOperation() are of type T.
To create an object of the class template, you need to define the data type within the < > when creating it.
className<dataType> classObject;
For example:
className<int> classObject; className<float> classObject; className<string> classObject;
The program uses a class template to perform addition, subtraction, multiplication, and division operations on two numbers
#include <iostream> using namespace std; template <class T> class Calculator { private: T num1, num2; public: Calculator(T n)1, T n2) { num1 = n1; num2 = n2; } void displayResult() { cout << "Numbers are: " << num1 << " and " << num2 << "." << endl; cout << "Addition is: " << add() << endl; cout << "Subtraction is: " << subtract() << endl; cout << "Product is: " << multiply() << endl; cout << "Division is: " << divide() << endl; } T add() { return num1 + num2; } T subtract() { return num1 - num2; } T multiply() { return num1 * num2; } T divide() { return num1 / num2; } }; int main() { Calculator<int> intCalc(2, 1); Calculator<float> floatCalc(2.4, 1.2); cout << "Int results:" << endl; intCalc.displayResult(); cout << endl << "Float results:" << endl; floatCalc.displayResult(); return 0; }
Output results
Int results: Numbers are: 2 and 1. Addition is: 3 Subtraction is: 1 Product is: 2 Division is: 2 Float results: Numbers are: 2.4 and 1.2. Addition is: 3.6 Subtraction is: 1.2 Product is: 2.88 Division is: 2
In the above program, a class template Calculator is declared.
The class contains two private members of type T: num1and num2as well as the constructor for initializing members.
It also contains public member functions to calculate the addition, subtraction, multiplication, and division of numbers, returning the value of the user-defined data type. Similarly, the function displayResult() outputs the final result to the screen.
In the main() function, two different Calculator objects intCalc and floatCalc for data types int and float are created: int and float. The constructor initializes the values.
Note that we use <int> and <float> when creating objects. These tell the compiler the data types to be used for class creation.
This will create a class definition for int and float separately, and then use them accordingly.
Then, displayResult() is called for both objects,
Then, call these two objects' displayResult(), which performs the calculator operation and displays the output.