Page 1 of 1
C++ class template function declaration and definition
Posted: Fri May 23, 2008 8:07 am
by Neo
Was recently trying to implement a templated class.
I initially had a header and implementation file but find that only unless the functions are implemented within the class itself does it compile and link properly.
Any ideas on why this is so? Is there a way to keep the definitions and declarations in separate files?
Posted: Fri May 23, 2008 9:14 am
by Korona
No, that is not possible (at least gcc cannot do that).
gcc will compile the template multiple times: Once for each parameter of the template. If the declaration and the implementation were in different files gcc would not know which parameter types are required when compiling the implementation file.
Posted: Fri May 23, 2008 1:03 pm
by JamesM
The export keyword was supposed to solve this, but hasn't been properly implemented yet.
Posted: Fri May 23, 2008 9:32 pm
by Neo
Thanks for the info.
So then this is the way the whole STL is implemented?
Posted: Fri May 23, 2008 9:52 pm
by neon
I use a trick around this:
Create a standard header file. This declares your template class. Have it #include your implementation header file (Mabey the last line in the file?). This header defines your template class routines. Create a source file that #includes the main header file, and it should work fine.
A little messy, but it allows us to separate interface from implementations for template classes.
Posted: Tue Jun 03, 2008 4:07 am
by bluecode
Neo wrote:You can have a little bit of magic by first defining a generic (void *-based, for example) container class with separately compiled implementation [...]
Just wanted to add this: You can instantiate member functions or the whole class for one particular type explicitly, via *drums* explicit template instantiation. For a whole class that looks like this: