C++ Template Class Declaration and Definition
C++'s templates are strong characteristics that let us create generic programs. We can use templates in two different ways:
- Class templates
- Function templates
Function Templates
In C++, function templates let you create generic functions with various data types. You design a single template that adapts to different types rather than creating separate functions for each form of data.
These template classes encourage code reuse and make maintenance easier. Template parameters represent the types involved, and the compiler creates unique versions of the function for each type. The C++ Standard Library extensively uses function templates for writing flexible and effective code.
Class Templates
Class templates in C++ provide the ability to create generic classes that function with many data types. You define a template class with type placeholders to avoid repeating code for numerous types, which encourages code reuse and preserves a constant interface.
Template parameters represent these types, and the compiler creates unique classes for each type. Class templates enable modification through specialization and are crucial for creating generic data structures (such as containers). They encourage extensible designs, reduce code duplication, and provide practical, type-safe solutions.
Template Class Declaration
In C++, a template class declaration presents a design pattern for producing adaptable and reusable classes. You can create a single class that adapts to several data types by utilizing placeholders known as template parameters, which encourages code efficiency and minimizes duplication.
The structure, member functions, and class variables are described in the template class declaration and placeholders for types. It is a base for generating specialized classes for various data types, enabling you to build adaptable and type-safe solutions.
A template class's declaration often has the following structure:
template <typename T>
class MyTemplateClass {
Public:
MyTemplateClass(T initialValue);
T getValue();
Private:
T data;
};
This class template has a T-type value. It has a function to get the value and a constructor to set the starting value. You can construct instances of this class with various data types using the T placeholder.
Example of template class declaration:
#include <iostream>
using namespace std;
// Now we are declaring a template class name as s
template <typename s>
class sample {
private:
s first;
s second;
public:
sample(s a, s b) : first(a), second(b) {}
s getFirst() const {
return first;
}
s getSecond() const {
return second;
}
};
int main() {
// Create objects of the template class
sample<int> nums(13, 58);
sample<double> doublenums(8.24, 9.34);
// Output the values stored in the objects
cout << "The Integer pair : " << nums.getFirst() << ", " << nums.getSecond() << endl;
cout << "The double number pair: " << doublenums.getFirst() << ", " << doublenums.getSecond() << endl;
return 0;
}
Output:
![C++ Template Class Declaration and Definition](https://static.tutorialandexample.com/cpp/cpp-template-class-declaration-and-definition1.png)
The above C++ code illustrates how to use the flexible template class sample. The s template parameter lets you create objects that contain pairs of values of various data kinds.
Within the class of the template:
- The Pair values are stored in the first and second private member variables.
- These variables are initialized by the constructor using the supplied values.
- The member methods getFirst() and getSecond() return the values that have been saved.
- In the main () function:
- By utilizing the sample template, the object nums and double-nums are produced.
- While doublenums save double values 8.24 and 9.34, nums store integer values 13 and 58.
- The saved values are shown with the help of the getFirst() and getSecond() functions.
Template Class Definition
Implementing a template class's member functions is part of the definition of the class. Usually, this goes in a separate.cpp file. The member functions of a template class are defined as follows:
template <typename T>
MyTemplateClass<T>::MyTemplateClass(T initialValue) : data(initialValue) {}
template <typename T>
T MyTemplateClass<T>::getValue() {
return data;
}
These lines let you create instances of the class, access the saved value, and implement the constructor and getValue method for the MyTemplateClass template.
Create a class template Object:
int main () {
ClassName<Type> objectName(value);
// ...
}
How to Use the Class Template
The class template must be instantiated by giving the correct data type to be used:
int main() {
ClassName<int> intInstance; // Instantiate with int data type
ClassName<double> doubleInstance; // Instantiate with double data type
intInstance.SomeMethod(42);
doubleInstance.SomeMethod(3.14);
return 0;
}
This class template becomes especially helpful when creating algorithms that handle various data structures like vectors, lists, and maps.
Example:
#include <iostream>
using namespace std;
// Class template
template <class S>
class sampleClass {
private:
S value; // Variable of type S
public:
sampleClass(S val) : value(val) {} // Constructor
S getValue() {
return value;
}
};
int main() {
// Create an object with an int type
sampleClass<int> num(7);
// Create an object with double type
sampleClass<double> doublenum(7.7);
// Output the values stored in the objects
cout << "Integer Value = " << num.getValue() << endl;
cout << "Double Value = " << doublenum.getValue() << endl;
return 0;
}
Output:
![C++ Template Class Declaration and Definition](https://static.tutorialandexample.com/cpp/cpp-template-class-declaration-and-definition2.png)
The above C++ code is an example of a class template called sampleClass. This template outlines a design for making objects that can hold values of various data kinds. The template has a function to retrieve stored values, a constructor for initialization, and private value storage.
The template is used to construct two objects, num (an int) and doublenum (a double), in the main () function. The value retrieval function of the template is used to assign values before they are shown.
Examples of Template Class Definition
#include <iostream>
using namespace std;
// Class template
template <typename T>
class Pair {
private:
T firstValue;
T secondValue;
Public:
Pair(T first, T second) : firstValue(first), secondValue(second) {}
T getFirstValue() const {
return firstValue;
}
T getSecondValue() const {
return secondValue;
}
};
int main() {
// Create an instance of Pair with int type
Pair<int> integerPair(10, 20);
// Create an instance of Pair with double type
Pair<double> doublePair(3.14, 2.71);
// Output the values stored in the pairs
cout << "Integer Pair Values: " << integerPair.getFirstValue() << ", " << integerPair.getSecondValue() << endl;
cout << "Double Pair Values: " << doublePair.getFirstValue() << ", " << doublePair.getSecondValue() << endl;
return 0;
}
Output:
![C++ Template Class Declaration and Definition](https://static.tutorialandexample.com/cpp/cpp-template-class-declaration-and-definition3.png)
Example1: Calculator program using Class Templates
#include <iostream>
using namespace std;
//Here we are creating a class template
template <typename s>
class sample {
public:
s plus(s q, s r) {
return q + r;
}
s minus(s q, s r) {
return q - r;
}
s multiply(s q, s r) {
return q * r;
}
s division(s a, s b) {
if (b == 0) {
cout << "Error: Division by zero!" << endl;
return 0;
}
return a / b;
}
};
int main() {
sample<int> num;
sample<double> doublenum;
int var1 = 49, var2 = 32;
double var3 = 34.5, var4 = 67.4;
//num calculations, which are integer
cout << "Integer Addition: " << num.plus(var1, var2) << endl;
cout << "Integer Subtraction: " << num.minus(var1, var2) << endl;
cout << "Integer Multiplication: " << num.multiply(var1, var2) << endl;
cout << "Integer Division: " << num.division(var1, var2) << endl;
// doublenum calculations
cout << "Double Addition: " << doublenum.plus(var3, var4) << endl;
cout << "Double Subtraction: " << doublenum.minus(var3, var4) << endl;
cout << "Double Multiplication: " << doublenum.multiply(var3, var4) << endl;
cout << "Double Division: " << doublenum.division(var3, var4) << endl;
return 0;
}
Output:
![C++ Template Class Declaration and Definition](https://static.tutorialandexample.com/cpp/cpp-template-class-declaration-and-definition4.png)
Example2: C++ class template with multiple parameters
Multiple parameter C++ class templates enable you to design flexible classes that accommodate various data types and additional values. You create templates for classes that give specialized functionality based on these inputs by combining types and non-type arguments.
#include <iostream>
using namespace std;
// Class template with multiple parameters
template <typename s, int num>
class Sample {
private:
s data[num]; // Array to store data
Public:
//Method to set data at a specific index
void action(int index, s value) {
if (index >= 0 && index < num) {
data[index] = value;
} else {
cout << "Index out of bounds!" << endl;
}
}
//Method to retrieve data from a specific index
s take(int index) const {
if (index >= 0 && index < num) {
return data[index];
} else {
cout << "Index out of bounds!" << endl;
return s();
}
}
};
int main() {
// Create an array of integers with size 6
Sample<int, 6> intArray;
// Set values
for (int i = 0; i < 6; ++i) {
intArray.action(i, i * 5);
}
// Display values
for (int i = 0; i < 6; ++i) {
cout << "Value at index " << i << ": " << intArray.take(i) << endl;
}
// Create an array of doubles with size 5
Sample<double, 5> doubleArray;
// Set values
for (int i = 0; i < 5; ++i) {
doubleArray.action(i, 3.14 * (i + 1));
}
// Display values
for (int i = 0; i < 5; ++i) {
cout << "Value at index " << i << ": " << doubleArray.take(i) << endl;
}
return 0;
}
Output:
![C++ Template Class Declaration and Definition](https://static.tutorialandexample.com/cpp/cpp-template-class-declaration-and-definition5.png)
The application of a class template with many arguments is demonstrated in the above-provided C++ program. By defining the data type and the array size, the template Sample enables the building of adaptable arrays. The main () Method creates instances of this template; doubleArray stores integers with a size of 6, whereas intArray stores double with a capacity of 6. The arrays are filled with values using the action() and take() methods. The example uses several arguments to highlight the importance of class templates, which let developers construct adaptable, reusable code for arrays of various data types and sizes.
Advantages of Template Class in C++
C++'s template classes have many benefits that add to the language's versatility and capability. The following are some significant benefits of using template classes:
- Reusability: You can create generic code operating on various data types using template classes. This reusability encourages code reuse and minimizes the need to write identical code many times for various data kinds.
- Generic Data Structures: Using template classes, one can build generic data structures like stacks, queues, trees, vectors, lists, and maps. These data structures have a uniform interface and can hold various kinds of data.
- Type Safety: Template classes offer type safety by enabling the compiler to apply type constraints at compilation time. This type of safety helps in the early detection of type-related errors during the development process.
- Performance Improvement: Templates type allows you to compile specialized code for data types, which may result in faster performance than runtime polymorphism.
- Polymorphism at Compile-Time: Template classes offer a type of polymorphism at compile-time in which the proper template specialization is chosen based on the supplied template arguments. Compared to runtime polymorphism, this may result in more effective code execution.
- Solving Complex Problems: By giving people flexible and expressive means to specify behavior, templates can help people tackle complex problems, including various data types or advanced type connections.
Conclusion
C++ class templates are vital for developers to create flexible and effective code. You can produce specialized versions of the class for various data types by building a single template class with placeholder types. These template classes encourage code reuse and minimize duplication.
Generic data structures and algorithms can be created using class templates, encouraging extendable and maintainable architectures. Utilizing the compiler's capacity to produce type-specific code simultaneously can improve efficiency and assure type safety. C++ programmers may create versatile and adaptable solutions using class templates that handle various data and programming contexts.