Labs ICT
🎓 SIWES/IT Login

Class Templates

1 min read | C++ Tutorial
🎓

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

C++ Class Templates

Class templates let you define generic data structures that work with any type. The type parameter is specified when creating an object. This is how STL containers like vector<int> or map<string, int> work internally. You can build your own reusable containers without sacrificing type safety.

#include <iostream>

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

int main() {
    Box<int> intBox(42);
    Box<std::string> strBox("hello");
    std::cout << intBox.getValue() << "\n";
    std::cout << strBox.getValue();
    return 0;
}