PDA

View Full Version : Templates : Help Please



sunil.thaha
14th February 2006, 12:06
Is there any issues if a template's implementation and declarations are in seperate files. I am using (GCC) 3.4.3 20041212 (Red Hat 3.4.3-9.EL4). In the Attachments below.
The TemplateTestError.tar.gz has Implemention of The Item::baseFunction() in Item.cpp and The TemplateTestSuccess.tar.gz has Implemention of The Item::baseFunction() in Item.h itself. Please not that the baseFunction() implemention is not an inline.

Please go through the Attachments;It would be great if some one could point out where i am going wrong. and Give links or tips on this Issue.

Thanks in Advance

Weaver
14th February 2006, 12:54
At the bottom of Item.cpp add the line:

template class Item<int>;


That tells the compiler to build code for that particular specialisation, otherwise when the compiler hits that file it doesn't know what's needed.

sunil.thaha
14th February 2006, 13:15
At the bottom of Item.cpp add the line:

template class Item<int>;


That tells the compiler to build code for that particular specialisation, otherwise when the compiler hits that file it doesn't know what's needed.

Ya that solves the problem but introduces a new one - It's not usable. I can expect the users of the Item class to type the class name in Item.cpp. There must be an elegant solution isn't it?. Moreover what if i plan to move the implemention to a .so/.dll file. Then what will they do .

If the implementation is kept in the .h The user even need not bother about the declaration - template class Item<int>;. But now they get to see the implementation and may be even change it .

I want the implementation to be put in the .cpp and leave the .cpp file intact. so that others can't mess things up.

Weaver
14th February 2006, 13:38
Well you can't stop people reimplementing your functions... they can always take your header and implement a new library =)


The problem with templates is that they're only generated "on demand". ie the specialisation of the function is only ever created if it's referred to. When the compiler sees Item.cpp it doesn't know what types of baseFunction() to generate. When it sees a reference it it in another cpp file, it can't see where the function is defined to create a specialisation.

Hopefully this explains it better:
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12


If you don't know ahead of time what types you'll need, then the best you can do is #include "Item.cpp" at the bottom of Item.h

sunil.thaha
14th February 2006, 14:50
Thanks That link solved all my doubts