开发者

Error Compiling Code After trying to turn a class into a template

开发者 https://www.devze.com 2023-02-11 04:33 出处:网络
1>main.obj : error LNK2019: unresolved external symbol \"public: __thiscall MyList<class Event>::~MyList<class Event>(void)\" (??1?$MyList@VEvent@@@@QAE@XZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall MyList<class Event>::~MyList<class Event>(void)" (??1?$MyList@VEvent@@@@QAE@XZ) referenced in function _main

Any idea what could be wrong? I had a working class before and then i tried to template it and i get this error above. Any idea ? I'm a little lost.

And in mai开发者_高级运维n i use this :

MyList<Event> eventManager;


Templates play oddly with C++'s compilation model because they aren't executable code - they're templates for executable code. Consequently, the standard model of partitioning a class into a .h/.cpp pair does not work correctly for templates.

The reason that you typically break apart a class into a .h file with the interface and the .cpp file with the implementation is that normally, .cpp files can be compiled separately while referencing code defined in other .cpp files because the linker will patch together all of the references after the files are compiled. Since all the .cpp compile down to object files containing executable code, everything will work out correctly.

With templates, however, this system breaks down. If you define a template class and then put all the implementations of its member functions into a .cpp file, then when the compiler compiles that file it won't find any code - just templates for code, and so it won't generate any object code for the template methods. Consequently, at link-time, you'll get errors for every member function you tried to call on the template class because there's no code available.

I don't know for sure if this is what's causing your particular error, but from what you're describing it looks like this is the case, especially since you changed a non-template class (probably split across a .h/.cpp pair) into a template class.

To fix this problem, the traditional C++ solution is just to have a .h file for the template without an accompanying source file. You can do this by just moving all of the code in the source file into the header. I like to put a line in the header marking where the interface stops and implementation begins, often something like

/* * * * * Implementation Below This Point * * * * */

or

/* * * * * Here be Dragons * * * * */

To make the point a bit clearer.

Hope this helps!


You most likely put the implementation of your function (in this case, the destructor) into a .cpp file. That won't work. When using with templates, the full function body needs to be accessible by anybody calling it, so you'll usually end up putting it into the .h file.

0

精彩评论

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