Archived

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

templates, separation cpp-file, h-file

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

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 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 on other sites
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 on other sites
Ah, ok, time to move everything back to the header file then...

Share on other sites
Only one compiler I know of is capable of handling export. Its kind of a thorn in C++''s side.

Share on other sites
And that compiler only refactors the code into C code before compiling, I believe.

1. 1
2. 2
3. 3
Rutin
21
4. 4
5. 5

• 14
• 30
• 13
• 11
• 11
• Forum Statistics

• Total Topics
631777
• Total Posts
3002306
×