Generic Class Templates

Started by
3 comments, last by UraniumRod 24 years, 1 month ago
I have gust begun to experiment with class templates, and I have come up to a linking problem. When I compile my program I get the error 'error LNK2001: unresolved external symbol "public: int _thiscall CTemplateClass[class OBJECT]::FreeObject(OBJECT **p)...', it continues on with some jibberish. Has any one had this problem before and knows how to fix it? I'd greatly apprecate it if some one could point me in the right direction. This is how the object is defined: template[typename OBJECT] class CTemplateClass : virtual public CMaintenance { . . . public: int FreeObject(OBJECT **p); . . . }; template[typename OBJECT] int CTemplateClass[OBJECT]::FreeObject(OBJECT **p) { . . . } The class is defined in the file CTemplateClass.h and the functions in CTemplateClass.cpp. the main() function in in the file main.cpp and includes CTemplateClass.h, it also has the file CTemplateClass.cpp included into the project as a source file. PS - Replace the square brackets ([]) with angle brackets. There seems to be a problem with using angle brackets in this MB. Edited by - UraniumRod on 3/10/00 10:05:54 PM
------------------------------"My sword is like a menacing cloud, but instead of rain, blood will pour in its path." - Sehabeddin, Turkish Military Commander 1438.
Advertisement
You''ve hit one of the most common problems in using templates. If you write your function bodies in the .cpp file, when the compiler builds that file, it has no idea what versions of the template you''ll be using. Thus, it doesn''t know what versions to build, and hence builds none of them. You should be able to use the ''export'' keyword before any template declarations in the .cpp file, but that''s VERY unlikely to work, as few C++ compilers support it.

Instead, you need to put all of your template functions into the .h file (many people just write them in the class declaration.) This way the compiler can see them when it''s building main.cpp, and has all the information it needs to build the functions.

-Brian
Thanks!
------------------------------"My sword is like a menacing cloud, but instead of rain, blood will pour in its path." - Sehabeddin, Turkish Military Commander 1438.
You do not need to write your functions in the .h file. All you need to do is include the .cpp file at the end of the .h file (which is like writing the functions in the .h file). Make sure to make use of #ifndef or else you will get stuck in loop (to .h includes the .cpp which includes the .h which includes the .cpp...).
Thanks to both of you Mike you just save me some time moving the functions into the .h file.
------------------------------"My sword is like a menacing cloud, but instead of rain, blood will pour in its path." - Sehabeddin, Turkish Military Commander 1438.

This topic is closed to new replies.

Advertisement