开发者

why a compiler can't find a template definition in .cpp [duplicate]

This question already has answers here开发者_如何学JAVA: Closed 11 years ago.

Possible Duplicate:

Why can templates only be implemented in the header file?

I'm wondering, why a c++ compiler is not able to instanciate a template class if it is defined in a .cpp file ?

EDIT: I am sorry but I have done a search before but answer to this apparently same question are "a compiler can't find a template definition in .cpp" but don't tell why. Except if i have bad read answers.


The C++ FAQ says it all:

  1. A template is not a class or a function. A template is a "pattern" that the compiler uses to generate a family of classes or functions.
  2. In order for the compiler to generate the code, it must see both the template definition (not just declaration) and the specific types/whatever used to "fill in" the template. For example, if you're trying to use a Foo, the compiler must see both the Foo template and the fact that you're trying to make a specific Foo.
  3. Your compiler probably doesn't remember the details of one .cpp file while it is compiling another .cpp file. It could, but most do not and if you are reading this FAQ, it almost definitely does not. BTW this is called the "separate compilation model."

http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12


Compilers process a single .cpp file at a time. Therefore, they are able to instantiate templates in a .cpp file, but only if they're defined in that same .cpp file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜