Sign in to follow this  
rogierpennink

C++ template problems

Recommended Posts

rogierpennink    400
Hey all, I'm making a simple queue class, using C++ templates. The odd thing is, whenever I compile the files that make the queue class (queue.cpp, queue.hpp) it compiles fine. Then, when I intend to use the queue in a simple console test program I get strange linker errors:
error LNK2001: unresolved external symbol "public: virtual __thiscall bd::Queue<class Omg>::~Queue<class Omg>(void)" (??1?$Queue@VOmg@@@bd@@UAE@XZ)
error LNK2001: unresolved external symbol "public: __thiscall bd::Queue<class Omg>::Queue<class Omg>(void)" (??0?$Queue@VOmg@@@bd@@QAE@XZ)
Note: The queue class is in the bd namespace. The test.cpp file is made as follows:
#include <iostream>
#include "test.h" // Includes queue.hpp etc.

using namespace bd;

int main( int argc, char **argv )
{
	std::cout << "Starting Burning Dawn Object test..." << std::endl;
	
	Queue<int> myQueue;
			
	return 0;
}

Although the queue class contains more methods and members, I will, for the sake of being short, only show the class with it's constructor/destructor and their implementations, because that is the only thing used in this test application...
/* queue.hpp */
namespace bd
{
	/**
	 * The queue class declaration. We use a templated class to allow
	 * for any datatype to be stored in the queue.
	 */
	template<class T>
	class Queue : public Object
	{
            public:
                Queue();
                ~Queue();
        };
}

/* queue.cpp */
template<class T>
bd::Queue<T>::Queue() : some_member( 0 )
{
}

template<class T>
bd::Queue<T>::~Queue()
{
// clean up..
}


Can anyone explain this? [Edited by - rogierpennink on May 4, 2007 7:55:18 AM]

Share this post


Link to post
Share on other sites
nmi    978
The compiler needs to know the implementation of a template to instantiate it. If you just provide the declaration in the header it cannot instantiate those functions, so no code for them is generated, and the linker will complain because it cannot find those symbols.

So either #include your .cpp in the end of the header or provide explicit template instantiations (if the types your template is used with is known in advance for instance).

Share this post


Link to post
Share on other sites
SunTzu    286
Don't #include the cpp file, but do take the template code out of the cpp file and put it in the h file instead.

Share this post


Link to post
Share on other sites
Perost    332
And I hope you're aware that C++ already has a standard queue container class, and are only writing this as an exercise.

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