How do I write class templates?

In C++, class templates allow you to create classes that can handle any data type. This is particularly useful for creating generic classes such as containers and algorithms. Below is an example of how to write a class template in C++.

template <typename T> class Box { private: T item; public: Box(T item) : item(item) {} T getItem() { return item; } }; int main() { Box<int> intBox(123); Box<std::string> strBox("Hello, world!"); std::cout << intBox.getItem() << std::endl; // Outputs: 123 std::cout << strBox.getItem() << std::endl; // Outputs: Hello, world! return 0; }

C++ class templates generic programming container classes C++ examples