问题
This thread has been really helpful, but I still have questions about this process that don't appear to be answered.
To what extent must I explicitly instantiate a template? For example, if in my definitions file I am using templates on every function, friend class, operator overload, etc, must I instantiate each in a template instantiation file (the current method that I am using)?
Based off of my trial and error, the answer appears to be no, and that a simple
template class Class<type>;
will work for all of the class's members. However, I have read code that suggests otherwise, and a concrete answer would be greatly appreciated.
回答1:
In general you don't need to explicitly instantiate a template, but just define it in a header file and include that header file. However, a common application of explicit template instantiation is when you want to "hide" the definition of a template. Imagine the following situation, in which for simplicity we hide the implementation of a template function:
header.h
template<class X> void f(); // declaration
header.cpp
#include "header.h"
template<class X> void f(){ /* definition */ }
template void f<int>(); // explicit instantiation for int, force the compiler to generate code
template void f<double>(); // explicit instantiation for double, same
main.cpp
#include "header.h"
int main()
{
f<int>(); // OK
f<double>(); // also OK
f<char>(); // linker error
}
As you can see, the function f
is defined in the header.cpp
file (and not in header.h
), and therefore the implementation is hidden from the user. Because of the explicit instantiations for int
and double
, the compiler will be able to find the code of f<int>()
and f<double>();
when compiling main.cpp
. However, when trying to find the code for f<char>();
when compiling main.cpp
, we get a linker error. That's because the compilation is done independently, and when the compiler compiles header.cpp
, the compiler only generates code for f<int>
and f<double>
, and doesn't know we will invoke f<char>
so it does not generate code for f<char>
.
The only catch is that in order to make use of such a code hiding, we must explicitly instantiate the function for all the types for which we want to use it, otherwise we get linker errors.
来源:https://stackoverflow.com/questions/32707522/explicit-instantiation-of-template