I have a class with several template member functions that I would like to distribute among several source files to speed up compilation times. (The templates are implementation details and are not intended to be used outside the class, hence their definition in sources not headers.)
How would I go about splitting up these templates in such a way that I will not get linker errors? If I have source file A using a template defined in source file B, how do I make sure t开发者_如何学Che appropriate instance of the template is constructed by the compiler?
I could not answer it better than C++ FAQ:
https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl
Simply don't declare those template items as part of the class in the header file. Then, define your templates only in the source file. For example:
MyClass.hpp
class MyClass
{
public:
void SomePublicMethod() const;
};
MyClass.cpp
template<class T>
void SomethingWithT(T myVal)
{
// ...
}
void MyClass::SomePublicMethod() const
{
SomethingWithT(42);
}
精彩评论