Sign in to follow this  
Woltan

Template Classes

Recommended Posts

Hey Folks, I have a question concerning the usage of template classes. I programmed a little template class like this:
//A.h
#include <stdlib.h>
template <typename T> class A
{
public:
A();
private:
int i;
};

//A.cpp
#include "A.h"
template <typename T> A<T>::A()
{
i = 0;
};

So far so good, everything "compiles" perfectly, but as soon as i start doing something like this:
//Test.cpp
#include "A.h"
void Test()
{
A<int*> *pO = new A<int*>;
}

The compiler cannot compile unless I also include the cpp file. My question to this community is, why the compiler somehow cannot access the other cpp file with the compiler. Any hint, link, tutorial is deeply appreciated!!! I really cannot understand what is going on, and I thought I'd know what templates are and how the compiler deals with them! Thx in advance for your help!! Cherio Woltan

Share this post


Link to post
Share on other sites
Unless your compiler supports the export keyword, and I'm willing to bet that yours doesn't, then you can't put the definition of a template in a separate source file without explicit instantiation for specific types. Without explicit instantiation, the complete definition of the template needs to be available at point of instantiation, which means, in effect, that the definition needs to go into the header. (Or an inline file of some sort, etc.)

Share this post


Link to post
Share on other sites
Heas SiCrane,
thanks for your help! I think i got the message. How about I put your message in my words, and you tell me if what i posted is correct.
When the compiler comes to compiling the template source in the cpp file, the definition of the template argument must be already made. (omg sorry for my poor english!)

How would you "solve" the poblem? Would you throw the cpp file away and just include all the source in the header file as well?

Thx for you help in advance!
Cheerz
Woltan

Share this post


Link to post
Share on other sites
Some uses files that includes all the implementation like in .cpp, and name it .inl (inline), because you include them in the include file and everything works fine...

So A.cpp became A.inl and you include it a the end of the class.

#include <stdlib.h>
template <typename T> class A
{
public:
A();
private:
int i;

#include "A.inl"
};

Hope it helps!

Share this post


Link to post
Share on other sites
Thx guys that did the trick.
Strange thing, but I thought I once had a template class that was working with a cpp file. Well anyways,
thx again!
cherio Woltan

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this