templates, separation cpp-file, h-file

Started by
4 comments, last by __fold 20 years, 6 months ago
Hi! I have this piece of code.

// HEADER FILE


namespace Mathlib {
	template <class Type>
	class Vector3  
	{
	private:
		Type vector[3]; //x, y, z


	public:
		// Constructors

		Vector3<Type>() {}
		
		// Destructor

		virtual ~Vector3<Type>() {}
		const bool			operator ==	(const Vector3& v);
      };
}

// CPP FILE   

   
#include "Vector3.h"

namespace Mathlib {
	template <class Type>
		const bool Mathlib::Vector3<Type>::operator == (const Mathlib::Vector3<Type>& v)
	{
		return (vector[0] == v.vector[0] && vector[1] == v.vector[1] && vector[2] == v.vector[2]);
	}
}
It works, but according to my book it shouldn't. It says that in the header file I should have.
      
export template<class Type>
What's this export thing and have I done something strange in my code? [edited by - __fold on October 15, 2003 4:49:41 AM]
Advertisement
Bullcrap, it works the way you''re doing it, so don''t you worry

----------------------------------------------
Petter Nordlander

"There are only 10 kinds of people in the world. They who understand binary and those who do not"
----------------------------------------------Petter Nordlander"There are only 10 kinds of people in the world. They who understand binary and those who do not"
Id guess its only working the way you are doing it because you arnt using the == operator, and so it isnt being instantiated.

You do need the export keyword to make your method work, but export isnt implemented in most compilers, and so you cant do it this way. Im sure your book explains why.

In short, when you use the operator==, the compiler needs to know the definition of the operator, and it also needs to instantiate the operator for the parameters your using it with, this cant be done when you place the definition in a seperate .cpp file, because the definition is compiled seperatly from the .cpp that your using it in, and so the correct definition cannot be instantiated. The compiler will leave a call to the linker instructing it to link the function called operator == with the parameter types your using, but the linker ont be able to find it, because it hasnt been instantiated, and so you will get a linker error

One solution is to #include"the .cpp file" at the BOTTOM of your header file.

Ah, ok, time to move everything back to the header file then...
Only one compiler I know of is capable of handling export. Its kind of a thorn in C++''s side.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
And that compiler only refactors the code into C code before compiling, I believe.
daerid@gmail.com

This topic is closed to new replies.

Advertisement