Thursday, August 4, 2016

the declarations and definitions of the class template

Q_0

 does the compiler compile the class(function) template in different way?

Q_1

 How does the compiler do in concreted details if two different exists?

Question here goes.




Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?


If all you want to know is how to fix this situation, read the next two FAQs. But in order to understand why things are the way they are, first accept these facts:
  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<int>, the compiler must see both the Foo template and the fact that you’re trying to make a specific Foo<int>.
  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.”
Now based on those facts, here’s an example that shows why things are the way they are. Suppose you have a template Foo defined like this:






No comments:

Post a Comment