Templates, VS 2005, multiple files.

Started by
1 comment, last by python_regious 18 years, 3 months ago
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...
If at first you don't succeed, redefine success.
Advertisement
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.
Ah, ok, I figured it might be something like this, thanks for the links [smile].
If at first you don't succeed, redefine success.

This topic is closed to new replies.

Advertisement