Sign in to follow this  
moo_gamer

Template Class Definition in .CPP

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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:


// Header
template <class T>
class MyClass
{

void myMethod();
};

// Source
template <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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this