Skip to main content
gamedev.net
🔒 Locked

template class

Started by conman 2 replies 350+ views
Original Post
conman
conman
I have a problem when seperating code and header in different files (.cpp/.h) of a template class. For example:
//Part 1 should be in the header file

template<class T>
class Test {
public:
  void test(void);
};

//Part 2 should be in the cpp file

template<class T>
void Test<T>::test(void) { ... }
 
If this example is put in one file everything compiles and links fine, but if I seperate the two parts I get a unresolved external linker error for every function of the class. Is there a way to do this? Thanks! -Constantin [edit: code tags don't work with < & >, use source tags] [edited by - Magmai Kai Holmlor on February 1, 2004 3:09:32 PM]
Firewalker
Firewalker
CPP file:


template<class T>
void Test<T>::Test(void)
{
// Body

}


also, make sure u link with the object file created by source.cpp.

Then, you need to declare the type of objects you will use as template arguments in the class while compiling it (ie: the following MUST reside in the header file, it will not work anywhere else in the code.) This will prevent the linker from choking because it can create the definitions for each template type while compiling source.cpp, resolving the linker errors.


template<class T>
class Test {
public:
void Test();
};
template class Test<MYTYPE1>;
template class Test<MYTYPE2>;
template class Test<MYTYPE3>;


[edited by - Firewalker on February 1, 2004 2:56:49 PM]
conman
conman
Thanks for the other threads I will read them!
And thanks for the tip with the declaration (but I cant't use that because I don't know the classes it will be used with..)


[edited by - conman on February 1, 2004 3:05:27 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.