Implementing Templates in Header File
Templates are a great feature of C++. In a few words, they allow programmers to create code that may work for several data types, while maintaining compilation-time checking. This is in a sense the best of both worlds, providing high performance and code reusability.
Despite the advantages, there are also problems with the generalized use of C++ templates. One of the problems is the increased compilation time. This is due to the fact that the compiler needs to see the template before it can do anything with it. In this article you will learn why templates are implemented on header files.
C and Header Files
First of all, header files are inherited from the C language. In C and in C++, a header file is needed to provide information that is shared by all compilation units (files) that require access to classes, function, name spaces, and external variables. The C language does this by direct inclusion of headers that specify such elements.
The C++ language maintained the use of C headers. However, they also added new elements called templates.
The difference between a function, for example, and a template, is that a function can be defined in a separate file. Only the declaration of the function needs to be known, so that goes in a header file. The implementation can be maintained separately.
This is not the case with templates. For a template to be used, the compiler needs to know its contents. Otherwise, there is no way to determine how code should be generated for a particular data type.
Because of this, most C++ templates are declared inside a header file. By doing this, programmers can reuse such templates in different files by just using an include directive.
While this is a simple procedure, having all this template code included in a header file creates extra work for the compiler. Therefore, it is always a good practice to have as little code in each header file. In this way, it is possible to organize headers in a more economic way, if necessary.
Post a comment