Question about C++ templates

I have a question about creating a c++ template class. I'm building a simple mailbox class for communication between threads, our original implementation simply used char buffers and size parameters to pass messages back and forth but I wanted something a little more robust.
My idea is to template the mailbox class so the user can use whatever sort of struct/class/primitive type they want as the communications path between threads.

My problem arises when I try to do this conversion. Previously we had a header file and a .cpp implementation file. So we would have something like:

Mailbox.h:
1
2
3
4
5
class Mailbox
{
  public:
    Mailbox_PushMessage(char* buffer, int bufferSize);
}


Mailbox.cpp:
1
2
3
4
Mailbox::Mailbox_PushMessage(char* buffer, int bufferSize)
{
  /* logic for Mailbox_PushMessage */
}


So I tried:
Mailbox.h:
1
2
3
4
5
6
template <typename T>
class Mailbox
{
  public:
    Mailbox_PushMessage(T &PushMessage);
}


Mailbox.cpp:
1
2
3
4
5
template <typename T>
Mailbox<T>::Mailbox_PushMessage(T &PushMessage)
{
  /* logic for Mailbox_PushMessage */
}


And it doesn't work.
It looks like the "typename T" in the implementation is being seen as different from the "typename T" in the header file.
If I put the implementation of all the Mailbox methods into the class declaration itself everything works fine. But I would prefer not to have the class declaration full of my implementation. Is there any way to get a template to work properly with a separate implementation file?

I've found one site that says that this is not possible, but I've looked through a number of books and tutorials and most of them show the method definition outside of the class declaration.
Am I missing something simple?
Last edited on
The declaration and the implementation have different arguments
'public' is with no capital 'P'
Last edited on
oops, that's not what's actually in my code, but I fixed the code above to be correct.
The whole thing compiles, but when I try to use it I get errors. For example:

1
2
3
4
5
6
7
8
9
10
typedef struct
{
   int unitOne;
   int UnitTwo;
}newMessageType;

int main()
{
   Mailbox<newMessageType> myMailbox;
}


Will say that Mailbox<newMessageType>::Mailbox() and Mailbox<newMessageType>::~Mailbox() are not defined. This is what led me to try putting the implementation in the header file.
If the implementation is in a different file it seems that the templated type "T" is not the same so no instance of the method is created for the type that the mailbox is being created with.


$10 say the problem is that you're declaring template functions in one file and defining them in another.
Seconded. Especially if you put the definition in a .cpp file. Write template code inline
Topic archived. No new replies allowed.