Reputation: 45414
Is there a way to pre-compile some template instantinations (of a class template) but not all, so that the remaining are compiled when instantinated (w/o errors at linking)?
To demonstrate the issue, consider this example:
// file.h
template<typename T> class object { /* lots of code */ };
// file.inc
template<typename T>
object::object(const T*data) { /* ... */ }
// and more: definitions of all non-inline functionality of class object<>
// file.cc to be compiled and linked
#include "file.h"
#include "file.inc"
template struct<int>;
template struct<double>;
// user.cc
#include "user.h"
#include "file.h"
object<double> x{0.4} // okay: uses pre-compiled code
object<user_defined> z(user_defined{"file.dat"}); // error: fails at linking
If instead the user #include
s "file.inc"
// user.cc
#include "user.h"
#include "file.h"
#include "file.inc"
object<double> x{0.4} // error: duplicate code
object<user_defined> z(user_defined{"file.dat"}); // okay
the compiler will find another compiled version due to the pre-compiled code from file.cc
.
So how can I avoid both of these problems? I reckon a related question would be "how can I specify that a pre-compiled header fully compiles a template for certain template parameters (only)?"
Upvotes: 0
Views: 66
Reputation: 93264
You can use extern template
to prevent a particular instantiation of a template in a given TU.
// src0.cpp
template class foo<int>;
// Oblige instantiation of `foo<int>` in this TU
// src1.cpp
extern template class foo<int>;
// Prevent instantiation of `foo<int>` in this TU
As long as src0
and src1
are linked together, your program will work.
Upvotes: 1