|
||||
Section 35:
|
[35.12] 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:
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: template<typename T> class Foo { public: Foo(); void someMethod(T x); private: T x; };Along with similar definitions for the member functions: template<typename T> Foo<T>::Foo() { ... } template<typename T> void Foo<T>::someMethod(T x) { ... }Now suppose you have some code in file Bar.cpp that uses Foo<int>: // Bar.cpp void blah_blah_blah() { ... Foo<int> f; f.someMethod(5); ... }Clearly somebody somewhere is going to have to use the "pattern" for the constructor definition and for the someMethod() definition and instantiate those when T is actually int. But if you had put the definition of the constructor and someMethod() into file Foo.cpp, the compiler would see the template code when it compiled Foo.cpp and it would see Foo<int> when it compiled Bar.cpp, but there would never be a time when it saw both the template code and Foo<int>. So by rule #2 above, it could never generate the code for Foo<int>::someMethod(). A note to the experts: I have obviously made several simplifications above. This was intentional so please don't complain too loudly. If you know the difference between a .cpp file and a compilation unit, the difference between a class template and a template class, and the fact that templates really aren't just glorified macros, then don't complain: this particular question/answer wasn't aimed at you to begin with. I simplified things so newbies would "get it," even if doing so offends some experts. Reminder: Read the next two FAQs for some solutions to this problem. |