"Normally, you declare functions and classes in the. h file and place their definitions in a separate. cpp file. However, when using a template, this kind of habitual practice will no longer be useful, because when instantiating a template, the compiler must see the exact definition of the template, not just its declaration. Therefore, the best way is to place the template statements and definitions in the same. h file. This is why all STL header files contain template definitions ." [1]
"The standard requires the compiler to view its definition entity in the context when instantiating a template. In turn, before seeing the instantiation template, the compiler does not process the template's definition body-the reason is very simple. How can the compiler know in advance what the typename real parameter is? Therefore, the template instantiation and definition must be placed in the same translation unit. "[1]
"Chapter 15th of C ++ programming ideology (page 1) explains the reasons:
The template definition is special. By template <…> Anything that is processed means that the compiler does not allocate storage space for it at the time, and it remains in the waiting state until it is notified by a template instance. In a compiler and connector, there is a mechanism to remove multiple definitions of a specified template. For ease of use, all template statements and definitions are almost always placed in the header file. "[2]
"For the C ++ compiler, when calling a function, the compiler only needs to see the declaration of the function. When defining objects of the class type, the compiler only needs to know the class definition, rather than the implementation code of the class. Therefore, the class definition and function declaration should be placed in the header file, while the definition of common functions and class member functions should be placed in the source file.
However, when processing template functions and class templates, the problem has changed. To instantiate template functions and class templates, the compiler must be able to view their definition objects in the context when instantiating the template. In turn, before seeing the instantiation template, the compiler does not process the template's definition body-the reason is very simple. How can the compiler know in advance what the typename real parameter is? Therefore, the template instantiation and definition must be placed in the same translation unit. "[3]
[1]20 C ++ tips. http://www.uml.org.cn/c++/20112284.asp applicable at any time
[2] Why cannot I separate the declaration of a class template from the class template function? http://blog.sina.com.cn/s/blog_684355870100jmjr.html?
[3] class template and template function connection error handling-http://www.cppblog.com/kenny/archive/2011/04/23/144841.html
[4] zhihu has an example that can achieve separate compilation, but it is not user-friendly... Http://www.zhihu.com/question/20630104