C++ class template function declaration and definition

Programming, for all ages and all languages.
Post Reply
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

C++ class template function declaration and definition

Post 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?
Only Human
Korona
Member
Member
Posts: 1000
Joined: Thu May 17, 2007 1:27 pm
Contact:

Post 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.
User avatar
JamesM
Member
Member
Posts: 2935
Joined: Tue Jul 10, 2007 5:27 am
Location: York, United Kingdom
Contact:

Post by JamesM »

The export keyword was supposed to solve this, but hasn't been properly implemented yet.
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

Post by Neo »

Thanks for the info.
So then this is the way the whole STL is implemented?
Only Human
User avatar
neon
Member
Member
Posts: 1567
Joined: Sun Feb 18, 2007 7:28 pm
Contact:

Post 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.
OS Development Series | Wiki | os | ncc
char c[2]={"\x90\xC3"};int main(){void(*f)()=(void(__cdecl*)(void))(void*)&c;f();}
User avatar
bluecode
Member
Member
Posts: 202
Joined: Wed Nov 17, 2004 12:00 am
Location: Germany
Contact:

Post 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:

Code: Select all

template class Vector<void*>;
Post Reply