Why C ++ template can only be achieved in the header file?

Define and implement a template class must be in the same file, usually a header file, the compiler to see the template in order to achieve the expanded template.

Because initialize a template, the compiler creates a new class based on the parameters of the template. such as:

Foo {templatestruct
T bar;
void doSomething (T param) {/ * do the using Stuff T /}};
// Somewhere in .cpp A
Foo F;
compilers when parsing the code, a new class is created, and the like It is equivalent to:
struct FooInt {
int bar;
void doSomething (int param) {/ do Stuff the using int * /}}
when the compiler needs access method implemented, when using the template parameters to instantiate them, such as this case is int. If the implementation is not in the header file by visiting invisible, so the compiler can not instantiate the template. Commonly used method is declared in the header file template to achieve those classes in a template file. Then the file contains specific implementation at the end of the header file. E.g.
// Foo.htemplate struct Foo {
void doSomething (T param);};

#include “Foo.tpp”

Foo.tpptemplate void Foo :: doSomething // (T param) {
// Implementation}
Thus, implementation and declarations are separated, access to the compiler.

发布了38 篇原创文章 · 获赞 13 · 访问量 4323

Guess you like

Origin blog.csdn.net/YanWenCheng_/article/details/103994668