Forcing templates to compile

Started by
2 comments, last by Sharlin 19 years, 2 months ago
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.
Advertisement
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.
Lucas Henekswww.ionforge.com
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).
Kippesoep
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, floattemplate 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 instantiationfd.bar(); // This doesn't, as usual

This topic is closed to new replies.

Advertisement