Jump to content
  • Advertisement
Sign in to follow this  
RaptorZero

C++ template class (solved)

This topic is 4355 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!