Unlocking the Power of C++ Templates

The Magic of Class Templates

Class templates enable you to create a single class that can work with different data types, making your code more concise and manageable. By using class templates, you can avoid writing multiple classes for different data types, reducing code duplication and increasing efficiency.

Declaring a Class Template

A class template declaration starts with the template keyword, followed by template parameters inside angle brackets (<>). The class declaration follows, with a member variable and a member function defined inside the class body. The template argument T is a placeholder for the data type used.

template <typename T>
class ClassName {
    // class body
};

Creating a Class Template Object

Once you’ve declared and defined a class template, you can create its objects in other classes or functions using the following syntax: ClassName<DataType> objectName;. For example, Number<int> numInt; creates a class definition for int data type.

Example 1: C++ Class Templates in Action

Let’s create a class template Number with a member variable num and a member function getNum(). We’ll then create objects of this class template using int and double data types.

template <typename T>
class Number {
    T num;
public:
    Number(T n) { num = n; }
    T getNum() { return num; }
};

int main() {
    Number<int> numInt(10);
    Number<double> numDouble(10.5);
    //...
}

Defining a Class Member Outside the Class Template

If you need to define a function outside the class template, you can do so using the following syntax: template <typename T> ReturnType ClassName<T>::functionName() {... }. This is necessary to specify the template parameter T again.

Example 2: Building a Simple Calculator Using Class Templates

Let’s create a class template Calculator that performs addition, subtraction, multiplication, and division of two variables num1 and num2. We’ll use int and float data types in this example.

template <typename T>
class Calculator {
    T num1, num2;
public:
    Calculator(T n1, T n2) { num1 = n1; num2 = n2; }
    T add() { return num1 + num2; }
    T subtract() { return num1 - num2; }
    //...
};

int main() {
    Calculator<int> calcInt(10, 5);
    Calculator<float> calcFloat(10.5, 5.2);
    //...
}

C++ Class Templates with Multiple Parameters

In C++, you can use multiple template parameters and even specify default arguments for those parameters. Let’s create a class template ClassTemplate with three parameters, one of which has a default type char.

template <typename T, typename U, typename V = char>
class ClassTemplate {
    T var1;
    U var2;
    V var3;
public:
    //...
};

int main() {
    ClassTemplate<int, double> obj1;
    ClassTemplate<double, char, bool> obj2;
    //...
}

With class templates, you can write more flexible and reusable code, making your C++ programming experience more efficient and enjoyable.

Leave a Reply