Archived

This topic is now archived and is closed to further replies.

__fold

templates, separation cpp-file, h-file

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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"

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites