Note that there are some explanatory texts on larger screens.

plurals
  1. POTemplates: Use forward declarations to reduce compile time?
    text
    copied!<p>I have to deal with a library that consists of many templated classes, which are of course all implemented in header files. Now I'm trying to find a way to reduce the unbearably long compile times that come from the fact that I pretty much have to include the whole library in each and one of my compilation units.</p> <p>Is using forward declarations a possibility, despite the templates? I'm trying something along the lines of the example below, where I attempted to get around the <code>#include &lt;vector&gt;</code>, as an example, but it's giving me a linker error because <code>push_back</code> is undefined. </p> <pre><code>#include &lt;iostream&gt; namespace std { template&lt;class T&gt; class vector { public: void push_back(const T&amp; t); }; } int main(int argc, char** argv) { std::vector&lt;int&gt;* vec = new std::vector&lt;int&gt;(); vec-&gt;push_back(3); delete vec; return EXIT_SUCCESS; } $ g++ fwddecl.cpp ccuqbCmp.o(.text+0x140): In function `main': : undefined reference to `std::vector&lt;int&gt;::push_back(int const&amp;)' collect2: ld returned 1 exit status </code></pre> <p>I tried precompiled headers once but that didn't change the compile times at all (I did make sure they were indeed loaded instead of the real headers). But if you all say that precompiled headers should be the way to go then I'll give that a try again.</p> <p><strong>UPDATE:</strong> Some people say it's not worth to forward-declare the STL classes. I should stress that the STL <code>vector</code> above was just an example. I'm not really trying to forward-declare STL classes, but it's about other, heavily templated classes of some library that I have to use.</p> <p><strong>UPDATE 2:</strong> Is there a way to make above example actually compile and link properly? Logan suggests to use <code>-fno-implicit-templates</code> and put <code>template class std::vector&lt;int&gt;</code> somewhere, presumably into a separate <code>.cpp</code> file that gets compiled with <code>-fno-implicit-templates</code>, but I still get linker errors. Again, I'm trying to understand how it works for <code>std::vector</code> so that I can then apply it to the templated classes that I'm actually using. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload