Sign in to follow this  

Forcing templates to compile

This topic is 4686 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

From what I know, it seems that a template code will only be compiled if it is used, but can you force it to compile all functions for a certain template parameter? This is because VC++ 8 compiles each cpp in it's own obj, and if a template is only defined once you will get link errors in other cpp sources.

Share this post


Link to post
Share on other sites
Only compiling what is used is one of the benefits of templates. If you dont use it, then it wont compile it, and the linker wont need to link it. I would suggest you post the linker error.

Also, template code should be in a .h file, not a cpp file, which is probably your problem in the first place.

Share this post


Link to post
Share on other sites
To qualify what lucinpub said: while the standard allows for separation of declaration and implementation of templates, there is only one compiler that supports this (Comeau, IIRC). For every other compiler, you're going to have to put declaration and implementation in the same translation unit (which often means the header file).

Share this post


Link to post
Share on other sites
Actually, there *is* a standard way to force the compiler to instantiate a template, and indeed, those instances are then available in other compilation units just like ordinary classes. The magic goes:


// foo.h:
template <typename T>
class foo
{
int bar();
};

// force instantiation for int, float
template class foo<int>;
template class foo<float>;

// foo.cpp
#include "foo.h"
template <typename T>
int foo<T>::bar()
{
...
}

// other.cpp
#include "foo.h"
...

foo<int> fi;
foo<double> fd;

fi.bar(); // This works now because of the forced instantiation
fd.bar(); // This doesn't, as usual


Share this post


Link to post
Share on other sites

This topic is 4686 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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