-1

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.

Community
  • 1
  • 1
Guillaume Paris
  • 10,303
  • 14
  • 70
  • 145
  • 1
    Please don't post the same question again and again. The answer is not going to be different. – Jon Apr 11 '11 at 11:19
  • 1
    Have you read the duplicates of your last question? If so, you should be able to make this question more specific. You might also want to read [this site](http://www.parashift.com/c++-faq-lite/templates.html). – Björn Pollex Apr 11 '11 at 11:19
  • Oh, there are dozens of questions asking this here on StackOverflow! Please try using the search before asking your question. – Oliver Charlesworth Apr 11 '11 at 11:19
  • 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. – Guillaume Paris Apr 11 '11 at 11:22

2 Answers2

1

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

Jonas Bötel
  • 4,452
  • 1
  • 19
  • 28
0

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.

MSalters
  • 173,980
  • 10
  • 155
  • 350