Sign in to follow this  
RaptorZero

C++ template class (solved)

Recommended Posts

[solved] Ok guys, it seems I'm having trouble with a template class even after some hours trying to make it work. I've been able to simplify the code to a few lines that still gives me the same error so here it goes: foo.h
template<class T>
class Foo
{
public:
	void F(void);
};



foo.cpp
#include "foo.h"

template<class T>
void Foo<T>::F(void)
{
	return;
}



main.cpp
#include "foo.h"

int main(void)
{
	Foo<int> A;
	A.F();

	return 0;
}



Judging by the simplicity of the code I think it might be a really stupid mistake so be nice to me (I've tryied, believe me). The problem is the compiler (MSVC Toolkit 2003) gives me an 'unresolved external symbol' for that function F used in main. Any help is appreciated, thanks! [Edited by - RaptorZero on October 21, 2006 6:23:41 PM]

Share this post


Link to post
Share on other sites
MSVC does not do template instantiation at linkage time, so the definition of the template member functions needs to be available at use time. Thus, add #include "foo.cpp" to the bottom of foo.h, and you'll be fine. Templates are treated like inline functions in this regard.

Share this post


Link to post
Share on other sites
Quote:
Original post by RaptorZero
Damn compiler forcing me to include a cpp file...


The compiler doesn't know the difference between a .h and a .cpp file. As far as it is concerned, a file is a file. When you #include something, the contents of the file included get merged into the stream of data that is sent to the compiler.

The thing with templates is that, just like inline functions, their code must be accessible from the point where they are used, since it is when the compiler is going to turn the template into "real" non-template code.

Which is why templates are always* kept in header files if they are going to be shared by multiple source files.

* - well, almost always.

Share this post


Link to post
Share on other sites
My complaint about including a cpp was because of having to remove the 'compile' and 'link' options for it inside the IDE, what is kind of a hack.

It seems the templates mechanics makes more sense now, thanks for the explanation.

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