C++ template class (solved)

Started by
3 comments, last by RaptorZero 17 years, 6 months ago
[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]
error C2065: 'signature' : undeclared identifier
Advertisement
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.
enum Bool { True, False, FileNotFound };
Really strange but it works, thanks a lot!
Damn compiler forcing me to include a cpp file...
error C2065: 'signature' : undeclared identifier
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.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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.
error C2065: 'signature' : undeclared identifier

This topic is closed to new replies.

Advertisement