Hello guys,
I am a bit stuck here :
My class vector has x,y,z and these values can be double or int .
I have other functions that add two vectors together which works fine if i am passing two vectors of the same type . What i am trying to solve here is passing one vector as double and the other as int .
I thought Operator overload would do it but it didnt work.
I hope someone can suggest something .
Thanks
If, for some reason, you're not using templates you could write a function to convert vector of ints to vector of doubles: vec_double(const vec_int& v) : x(v.x), y(v.y), z(v.z){}
This is just like a copy constructor. Now the function you wrote to add vec_double will work for vec_int too.
The last way would be to actually write four functions ( int + int, int + double, double + int and double + double ) but that's what templates are for.
The above is ok, but it requires that B be convertible to A, or more specifically, in the
expression
a + b
where a and b are vectors, that the right-hand side's contained type be convertible
to the left-hand side's contained type.
It also somewhat breaks the commutative rule in that a + b != b + a.
To solve both of the above problems, you need a bit more template machinery that
can pick the correct type of the resulting vector given two contained types.
My guess though is that all of this is well beyond what you're looking for.
I dont this this is how it should be , but heres the error:
1>c:\users\elkhas\documents\visual studio 2010\projects\final\final\vectror.h(41): error C2244: 'vector<T>::plus' : unable to match function
ok i got it to work now with two parameters T and U
This is how it should be:
template<class T>
template<class U>
vector<T> vector<T>::plus(const vector<U>& vec)
{
vector<T> result(x+vec.x,y+vec.y,z+vec.z);
return result;
}
This article helped :http://www.cplusplus.com/forum/general/19017/
But i am still getting error when i pass vector<int> a(1,2,3); and vector<double> b(1,2,3) to the plus function it tells me i cant add double to int which is what i am trying to solve.
I'm saying that unless you are using a compiler that supports C++0x's decltype keyword, then
you have a big problem. Essentially, given T and U, you have to implement the compiler's promotion
rules and determine whether the result of the expression should be a vector<T> or a vector<U>.
But that will require a _LOT_ of template machinery.