C++ templates and Java generic classes are nearly identical in syntax and usage. However, C++ templates are more extensive or powerful than Java generics in two ways:
Much like function arguments generalize data, templates generalize data types. "Regular" function arguments act as placeholders for data passed into the function when the program calls it at runtime. Template variables are also placeholders, but the program replaces them with data type names. All valid data types, including all fundamental types like char, int, and double, and structure and class names, can replace a template variable. However, the replacement can't occur before the user specifies the replacement type. To satisfy this requirement, programmers place templates in header files where the compiler processes them after the user-specified types replace the template variables.
template <class T> int min(T v1, T v2) { ... } |
template <typename T> int min(T v1, T v2) { ... } |
template <class T> class stack { private: T st[100]; public: void push(T data); }; |
template <typename T> class stack { private: T st[100]; public: void push(T data); }; |
template <class T> void stack<T>::push(T data) { ... } |
template <typename T> void stack<T>::push(T data) { ... } |
Stack<int> stack1; |
Stack<Employee> stack2; |