Template Class Definition in .CPP

Started by
6 comments, last by Rydinare 15 years, 11 months ago
Hi! All, I know, template class definition should in header files. But is there any way I can define funtions in .cpp? Thanks in advance.
Advertisement
Quote:Original post by moo_gamer
Hi! All,

I know, template class definition should in header files. But is there any way I can define funtions in .cpp? Thanks in advance.


Yes. You can be explicit about what instantiations your templates will export.

So, instead of this:

template <class T>class MyClass{   void myMethod()   {       ...   }};


You could have this:

// Headertemplate <class T>class MyClass{   void myMethod();};// Sourcetemplate <class T>void MyClass<T>::myMethod();{   ...}template class MyClass<int>;template class MyClass<double>;// ... etc ...


The benefit here is a significant reduction in compilation time. An improvement on this method, which I have employed in the past is to have the header file, the "source" file, and then the explicit template instantiations include the "source" file for compilation purposes, but nowhere else is the source included. This allows the modularity of defining new types later.
Export Keyword, however not all compilers support it.
Quote:Original post by fpsgamer
Export Keyword, however not all compilers support it.


VS2008 doesn't support it, correct?
Quote:Original post by Rydinare
Quote:Original post by fpsgamer
Export Keyword, however not all compilers support it.


VS2008 doesn't support it, correct?


Correct.

I ran into this recently.
[TheUnbeliever]
Quote:Original post by Rydinare
Quote:Original post by fpsgamer
Export Keyword, however not all compilers support it.


VS2008 doesn't support it, correct?


It doesn't, but the link I provided demonstrates a neat little way to get around that fact.
Quote:Original post by Rydinare
Quote:Original post by fpsgamer
Export Keyword, however not all compilers support it.


VS2008 doesn't support it, correct?


Comeau is still the only compiler I know of that supports export, but as discussed here, it's not quite what you would expect, and generally not worth it.
Quote:Original post by Driv3MeFar
Quote:Original post by Rydinare
Quote:Original post by fpsgamer
Export Keyword, however not all compilers support it.


VS2008 doesn't support it, correct?


Comeau is still the only compiler I know of that supports export, but as discussed here, it's not quite what you would expect, and generally not worth it.


Nice read. Thanks.

Judging by the drawbacks of export template, it doesn't seem to offer much.

This topic is closed to new replies.

Advertisement