Templates and operator overloading

I have a template class called Vector<T>.
If i've overloaded the * operator as shown here
1
2
template <class T>
Vector<T> operator*(const Vector<T>& v, const T& a);

(The overloading is outside the class)

Within int main(), im using Vector<int> objects.
I have a Vector object called X. When doing X = X*0 , i receive "no match for operator*"
How can i get the * overload to work with Vector<int> (and <int>) objects?
What should I write?

Thanks in advance
Last edited on
Sorry for the double posting.
After a while , i found the answer here
http://www.velocityreviews.com/forums/t285965-overloading-template-operator-arguments.html

Have you declared the above method a friend?

You need one of the following two declarations:

1
2
3
4
5
6
7
8
9
template< typename T >
class Vector {
   public:
      // either:
     friend Vector<T> operator*( const Vector<T>& lhs, T rhs );

     // or:
    Vector<T> operator*( T rhs ) const;
};


Note: you may also make rhs a const reference as you've done.
Thanks!

Although i ended up using the solution in www.velocityreviews.com , it's good to know different ways to attack a certain problem.

I'm marking this as solved.
Sorry for coming back to an already solved topic, but here's the answer i was looking for.

I can actually do
1
2
template <class T>
Vector<T> operator*(const Vector<T>& v, const T& a);


The problem appeared when i did X = X*1;
In linux, the problem does not exist. However, in windows' Dev C++, the operand 1 has to be typecasted, because 1 is not a float, but an int.

If X is Vector<float> , then i should write X = X*float(1)
Last edited on
That's a bit ugly.

Typically what is done is

1
2
template< typename T, typename U >
Vector<T> operator*( const Vector<T>& v, U u );


The idea being that if U is a type incompatible with T, the body of the function won't
compile for some reason. As opposed your solution, which still doesn't compile, but
gives a different compile error.

This allows you to do X = X * 1; without the typecast.
Now i understand why that works ^_^. I really like your idea.
Once again, thanks a lot.
Last edited on
1 is an integer. As a float it is 1.0f.
Topic archived. No new replies allowed.