extern template and compile time

g.gael@free.fr g.gael@free.fr
Fri Jun 13 17:06:00 GMT 2008


 Hi list,

Short version: I'd to know if there is a way to really avoid the
instantiation of a template class using "extern template"
such that the compilation time (and memory usage) get optimized.

Longer version:

To be more precise let's assume I have a template class Foo
entirely declared and defined in Foo.h:

  template class Foo {  
    void bar() { /* heavy code */}
  };  

Let's assume the code of Foo::bar takes age to compile. So I also
have a Foo.cpp file with a couple of explicit instantiation for the
most common types:

 template class Foo<int>;   
 template class Foo<float>;   
 template class Foo<double>;   
 // etc.

Now I have to tell gcc to not instantiate Foo for these types, so I
added the following extern template declarations at the end of Foo.h: 

 extern template class Foo<int>;   
 extern template class Foo<float>;   
 extern template class Foo<double>;   
 // etc.

Unfortunately this does not reduce the compilation time at all (I
mean the compilation of a single file using Foo.h, not Foo.cpp of
course !). The only effect is that the instantiated code is not put in
other .o object files. I also tried to replace the "extern" keyword by
"inline" or "static" with the same result.

However this works well with ICC (compilation time reduced by 3 in
my case), and according to several documentations of extern templates
(including C++0x spec) it seems that "extern template" should really behave
as I expected. (well maybe the best would be to only instantiate the struct
and inline members to still allow inlining, but that's another problem...
BTW, that might explain the current behavior of gcc ?).

So of course the workaround is to put the code of heavy members into a
separate file, e.g. Foo.hpp, which would be included by Foo.cpp only. Though
this works well, this is a little inconvenient because if the user uses a
non-common type, then he has to include Foo.hpp and he lost all the
compilation time benefits for common types (since extern still leads to an
instantiation in memory). Again he can add his own explicit instantiations in 
a separate file but that's even more inconvenient.

Hence my initial question: does there exist a better workaround ? and if not,
is there any plan to support extern template as suggested in the C++0x spec ?
(note that I might be wrong about the interpretation of the C++0x spec,
 no offense !)


Thanks a lot,

Gael.


   



More information about the Gcc-help mailing list