I am working on a template
function in a class
:
class Data {
public:
template <typename T>
std::byte* serialize(const T& object) { /* serialize */ }
};
and I noticed that Data::serialize<Object>
is instantiated in every compilation unit. For class
es I could do, e.g.
extern template class Class<Object>;
in the header file and place
template class Class<Object>
to instantiate the Class<Object>
only once and let the linker resolves the issue. Is there a way I do similar thing for functions and member functions?
CodePudding user response:
It works exactly the same.
Explicit instantiation declaration in the header:
extern template std::byte* Data::serialize<Object>(const Object&);
And explicit instantiation definition in one translation unit:
template std::byte* Data::serialize<Object>(const Object&);
(<Object>
is optional because it can be deduced from the const Object&
parameter.)
However, consider that while this may reduce compilation time, it can also negatively affect compiler optimizations, because you make it harder to inline the function (at least without link-time optimization). The resulting binary will contain only one definition of the function template specialization anyway, whether you use explicit instantiation or not.