From 44168039c079b09e4824c285b7262dc6284607b1 Mon Sep 17 00:00:00 2001 From: Nevemlaci Date: Wed, 12 Feb 2025 15:46:31 +0100 Subject: [PATCH] article about why templates must be in header files + alternative --- articles/template-header.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 articles/template-header.md diff --git a/articles/template-header.md b/articles/template-header.md new file mode 100644 index 0000000..74299fe --- /dev/null +++ b/articles/template-header.md @@ -0,0 +1,27 @@ +# Why can templates only be implemented in the header file? + +The only portable way of using templates at the moment is to implement them in header files by using inline functions. + +When instantiating a template, the compiler creates a new class/function with the given template argument. + +The compiler needs to have access to the implementation of the class methods or the function to instantiate them with the template argument. If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template. + +## Alternative solution + +Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need. + +```cpp +//foo.hpp +//no method implementations +template struct Foo { ... }; +``` + +```cpp +//foo.cpp +//implementation of Foo's methods here... + +//explicitly instantiate Foo with the needed template arguments +//you will only be able to use Foo with T=int and T=float +template class Foo; +template class Foo; +``` \ No newline at end of file