Sign in to follow this  

Templates, VS 2005, multiple files.

This topic is 4354 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

Ok, I'm not too hot at writing my own templated classes, so bear my ignorance. Essentially, I have problems when splitting things up into multiple files. Lets take a simple example:
template<typename T>
class TestClass
{
public:
	void Print( T test );
};

template<typename T> void TestClass<T>::Print( T test )
{
	cout<<test<<endl;
}

int main()
{
	TestClass<int> test_class;
	test_class.Print( 2 );
	return 0;
}

This works, all well and dandy. Now, if I just split that up into three files (a header with the class declaration, a source file with the implementation of the member function, and another source file with the main function) I get an "unresolved external error for void TestClass<int>::Print(int)". Now, I'm actually including the files and such, all being compiled and linked together - I'm not being that braindead - hopefully. Is there any reason why that shouldn't work? I'm at a loss here...

Share this post


Link to post
Share on other sites
Unless your compiler supports the export keyword, and MSVC doesn't, then you can't put the definition of a template in a separate source file without explicit instantiation for specific types. Without explicit instantiation, the complete definition of the template needs to be available at point of instantiation, which means, in effect, that the definition needs to go into the header. (Or an inline file of some sort, etc.)

For more details see these articles: "Export" Restrictions, Part 1 and "Export" Restrictions, Part 2.

Share this post


Link to post
Share on other sites

This topic is 4354 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.

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