Labs ICT
Pro Login

Class Templates

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;
}
Try it Yourself →