Templates and friend operator

P

Patrick Labatut

The following code should compile fine with g++ 3.3 and 3.4. However if
I instead put the friend operator* declaration right below the operator*
member, g++ 3.4 won't compile it anymore.

Could someone give me some explanation on this weird behaviour ?

/*************************************************************************/

template<class FloatT>
class Vector3;

template<class FloatT>
Vector3<FloatT> operator*(FloatT f, const Vector3<FloatT>& v);

template<class FloatT>
class Vector3 {
public:
Vector3(FloatT x, FloatT y, FloatT z)
{
this->v[0] = x;
this->v[1] = y;
this->v[2] = z;
}

friend Vector3<FloatT> operator*<>(FloatT f, const
Vector3<FloatT>& v);

FloatT operator*(const Vector3<FloatT>& v) const
{
return (this->v[0] * v.v[0]
+ this->v[1] * v.v[1]
+ this->v[2] * v.v[2]);
}

private:
FloatT v[3];
};

template<class FloatT>
Vector3<FloatT> operator*(FloatT f, const Vector3<FloatT>& v)
{
return Vector3<FloatT>(f * v.v[0], f * v.v[1], f * v.v[2]);
}

int main(int argc, char *argv[])
{
Vector3<float> v(0, 0, 0), w(0, 0, 0);

w = 2.0f * v;

return 0;
}
 
M

Micha

Hi Patrick,

could you send your error messages too? I'm having a
pretty much similar problem.

Micha
 
P

Patrick Labatut

could you send your error messages too?

yoohoo.cpp:24: error: declaration of `operator*' as non-function
yoohoo.cpp:24: error: expected `;' before '<' token
yoohoo.cpp: In function `Vector3<FloatT> operator*(FloatT, const
Vector3<FloatT>&) [with FloatT = float]':
yoohoo.cpp:40: instantiated from here
yoohoo.cpp:27: error: `float Vector3<float>::v[3]' is private
yoohoo.cpp:33: error: within this context
yoohoo.cpp:27: error: `float Vector3<float>::v[3]' is private
yoohoo.cpp:33: error: within this context
yoohoo.cpp:27: error: `float Vector3<float>::v[3]' is private
yoohoo.cpp:33: error: within this context

Some people I already asked told me they were getting similar error
messages with other compilers than g++ (however I don't know which
compilers they tried).
 
M

Marc

Patrick said:
Some people I already asked told me they were getting similar error
messages with other compilers than g++ (however I don't know which
compilers they tried).

Sun Studio:

Warning: A friend function with template-id name must have a template
declaration in the nearest namespace.
Where: While specializing "Vector3<float>".
Where: Specialized in non-template code.

Comeau:

error: function "Vector3<FloatT>::eek:perator*" is not a template
friend Vector3<FloatT> operator*<>(FloatT f, const Vector3<FloatT>& v);
^
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top