Demystifying C++ - Templates
Templates [1] are a fundamental feature of C++ essential for generic programming. They allow programmers to write code that is independent of the data type, enhancing the reusability of the code. Templates are not limited to simple data types; they can also be used with custom types such as classes and structures.
In C++, a template is introduced with the keyword template
, followed by a template parameter list in angle brackets (<>
). The compiler then creates a new function or class from the template when it encounters a declaration with a specific type. This technique is called template instantiation. The C++ to C compiler realizes templates through the duplication of code. For each template instance of a function or class, a variant is also generated in the C code. If a template is not used, it completely disappears from the code.
C++ templates enable the creation of functions that can work with any data type. Here's a simple example in C++:
Template Function | template <typename T> T max(T a, T b) { return (a > b) ? a : b; } void func() { int a = max<int>(10, 20); float f = max<float>(10.0, 20.0); ... } |
int max_int(int a, int b) { return (a > b) ? a : b; } float max_float(float a, float b) { return (a > b) ? a : b; } void func(void) { int a = max_int(10, 20); float f = max_float(10.0f, 20.0f); ... } |
---|---|---|
Template Class | template <class T, int N1, int N2> class Matrix { public: T data[N1][N2]; }; Matrix<int, 5, 5> m1; |
struct Matrix_int_3_5 { int data[3][5]; }; struct Matrix_int_3_5 m1; |