// vec2.h
template<class v_float=float>
class vec2
{
public:
v_float m[2];
};
template<class v_float>
vec2<v_float> operator* (v_float & f, vec2<v_float> & v);
template<class v_float>
vec2<v_float> vec2<v_float>::operator* (v_float & f, vec2 & v)
{
return vec2(v.m[0]*f, v.m[1]*f);
}
I want to overload the operator* for the above template class vec2, but the above code gave me the following error: vec2.cpp:68: error: ‘vec2 vec2::operator*(v_float&, vec2&)’ must take either zero or one argument
How to overload the operator*(float, vec2) for a template class? note that the number of parameters of operator* must be two.
I think the problem is in this template member function:
Since you’re defining
operator *as a member function here, C++ automatically assumes that the receiver object is one of the operands. This means that if you want to define multiplication, you should only be defining a function that takes one argument, namely, the right-hand side of the multiplication (since the left-hand side will be the receiver object).I think you meant to have this as a free function, as shown here:
Hope this helps!