You cannot separate declarations and definitions this way: if you cancel the definition of your specialized member functions in a separate .cpp file, regardless of whether you declare your specialization immediately after the main template, the compiler will not be able to instantiate, and the linker will complain unresolved links.
Typically, the definition of the member functions of a class template is contained in the header file, unless you specify the explicit creation of instances of the corresponding class templates:
template class X<int>;
In general, if you do not encounter really terrible compile-time problems, I suggest you follow the usual practice and put everything in the header file, which should be included with all translation units that should use the class template:
///////////////////// file A.hpp /////////////////////
If you run into really terrible compile-time problems, you can separate the definitions of a member function and put them in separate translation units with explicit instances, but in C ++ 11 there is no clean / easy way to make sure that all the specializations that you reject in separate .cpp files are declared immediately after the main template (a recommendation on good practice is recommended). If this were so, I think it would be so popular that you would not need to come here and ask about it, because everyone is faced with such a design problem.
In some cases, some trendy macros can help, but with doubt they will be more useful than pain in maintenance in really complex projects.
The solution to this problem was undertaken in the C ++ 03 standard by introducing the export keyword, but the implementation experience proved to be too difficult to support compiler providers, so export no longer part of C ++ Standard (starting with C ++ 11).
We hope that the best solution for modules will turn it into C ++ 14 and provide a solution for template design.
source share