Example: Say I include in my precompiled header file:
#include <vector>
As a few instances of the vector, such as std::vector, std::vector etc are used often in my project, will it reduce compile time if I instantiate them as well in the precomiled header like this:
#include <vector>
template class std::vector<float>;
template class std::vector<int>;
Going further, will it make sense to even add dummy functions to the precompiled headers which uses a few functions:
namespace pch_detail {
inline auto func() {
auto&& v = std::vector<float>{};
v.size();
v.begin();
v.front();
}
}
I'm a very unsure of of how translation units and templates really work, so it seems to me if I instantiate them in the precompiled headers, it should mean that they do not need to be instantiated for every .cpp file.
Update
Tested on a real-world code base with Visual Studio 2017 and some instantiations of commonly used template classes.
- With common templated class instantiated: 71731 ms
- Without instantiation: 68544 ms
Hence, at least in my case, it took slightly took more time.
It can make a difference yes.
Instantiation in translation units can then exploit data in the precompiled header, and a compiler can read that more quickly than the C++ standard library headers.
But you will have to maintain a list of instantiations, so this compile-time optimisation might be more trouble than it's worth - your idea could end up having the opposite effect if you have instantiations that are no longer needed.