0
0
CppHow-ToBeginner · 3 min read

How to Create Class Template in C++: Syntax and Example

To create a class template in C++, use the template<typename T> keyword before the class definition. This allows you to define a class that works with any data type specified when you create an object of that class.
📐

Syntax

A class template starts with the template<typename T> declaration, where T is a placeholder for any data type. The class uses T as a type inside its definition. When you create an object, you specify the actual type to replace T.

  • template<typename T>: Declares a template with a type parameter T.
  • class ClassName: Defines the class using T as a type.
  • T member;: Use T inside the class to represent the generic type.
cpp
template<typename T>
class ClassName {
public:
    T member;
    ClassName(T val) : member(val) {}
    T get() { return member; }
};
💻

Example

This example shows a simple class template Box that stores a value of any type and returns it with a get method.

cpp
#include <iostream>
#include <string>

template<typename T>
class Box {
public:
    T value;
    Box(T val) : value(val) {}
    T get() { return value; }
};

int main() {
    Box<int> intBox(123);
    Box<std::string> strBox("Hello");

    std::cout << intBox.get() << std::endl;
    std::cout << strBox.get() << std::endl;
    return 0;
}
Output
123 Hello
⚠️

Common Pitfalls

Common mistakes when creating class templates include:

  • Forgetting the template<typename T> line before the class definition.
  • Not specifying the type when creating an object, e.g., Box b(5); instead of Box<int> b(5);.
  • Using T incorrectly inside the class, such as trying to use it as a value instead of a type.
cpp
/* Wrong: Missing template declaration */
// class Box {
// public:
//     T value; // Error: T is undefined
// };

/* Correct: Include template declaration */
template<typename T>
class Box {
public:
    T value;
};
📊

Quick Reference

Remember these tips when working with class templates:

  • Always start with template<typename T>.
  • Use T as a placeholder type inside your class.
  • Specify the actual type when creating objects, like Box<int>.
  • Class templates help write reusable code for different data types.

Key Takeaways

Use template<typename T> before the class to create a class template.
Inside the class, use T as a placeholder for any data type.
Specify the actual type when creating objects from the template class.
Class templates enable writing flexible and reusable code for multiple types.
Always include the template declaration to avoid compilation errors.